C file operation

xiaoxiao2021-03-05  20

13.3 Opening and Close

The file is turned on before making a read and write operation, and it is necessary to turn it off. The so-called open file is actually a variety of information for establishing a file, and makes the file pointer to the file for other operations. The shutdown file is disconnected between the pointer and the file, or the file is prohibited.

In the C language, the file operation is done by the library function. The main file operation functions will be introduced in this chapter.

13.3.1 Open (FOPEN Function) The Fopen function is used to open a file, and the general form of the call is:

File pointer name = fopen (file name, usage file mode);

among them,

"File Penname" must be a pointer variable that is illustrated as a File type;

"File Name" is the file name that is opened;

"Using file mode" refers to the type and operational requirements of the file.

"File Name" is a string constant or a string array.

E.g:

File * fp;

FP = ("File A", "R");

Its significance is to open the file file a in the current directory, only "read" operation is allowed, and the FP points to the file.

As another example:

FILE * FPHZK

FPHZK = ("c: // hzk16", "rb")

Its meaning is to open the file HZK16 under the root directory of the C drive disk, which is a binary, only allowing a second-way way to read operation. The first represents the escape character in the two anti-slope "//", the second represents the root directory.

There are 12 ways to use files, and their symbols and significance are given below.

File Usage Significance "RT" Read only opens a text file, only allow reading data "WT" only writes to open or create a text file, only allowing writing data "AT" to add a text file, and write data at the end of the file " RB "Read only opens a binary, only allows reading data" WB "only writes to open or establish a binary file, only allowing write data" ab "to add a binary file, and write data" RT "in the end of the file A text file, allow reading and writing "WT " to read or create a text file, allow reading and writing "AT " to read a text file, allow reading, or add data "RB " reading and writing a binary File, allow reading and writing "WB " to read or create a binary, allow reading and writing "AB " to open a binary file, allow reading, or add data at the end of the file

The following description for file usage:

1) File usage is made from R, W, A, T, B, six characters, and the meaning of each character is:

R (Read): Read

W (write): Write

A (append): append

t (text): Text file, can omit

B (banary): binary file

: Read and write

2) When you use "R" to open a file, the file must already exist and can only be read from the file.

3) The file that opens with "W" can only be written to the file. If the open file does not exist, establish the file with the specified file name. If the open file already exists, remove the file and rebuild a new file.

4) To add new information to an existing file, you can only open the file in a "A" mode. But this file must be existing, otherwise it will be wrong.

5) When a file is opened, if an error, the FOPEN will return a null pointer value NULL. This information can be used in the program to discriminate whether the operation of the open file is completed and processed accordingly. So open the files using the following blocks:

6) IF ((fp = fopen ("c: // hzk16", "rb") == null) {

Printf ("/ NERROR ON Open C: // HZK16 File!");

Getch ();

Exit (1);

}

The meaning of this program is that if the returned pointer is empty, it means that the HZK16 file in the root directory cannot be opened, then the prompt information "Error On C: / HZK16 File!", The next line getCH () function It is a character from the keyboard, but is not displayed on the screen. Here, the role of this line is waiting, only the program continues only when the user is knocking from the keyboard, so the user can use this waiting time to read an error prompt. After the key is keys to execute the exit (1) exit program.

7) When reading a text file into the memory, the ASCII code is converted into a binary code, and when writing the file in a text, it is also necessary to convert the binary code to the ASCII code, so the reading and writing of the text file is more Multi-conversion time. This conversion does not exist for the reading and writing of binary files.

8) Standard input file (keyboard), standard output file (display), standard error output (error message) is opened by the system and can be used directly.

13.3.2 File Close Function (FClose Function) File Once used, the application closes the file to the file to avoid errors such as data loss of the file.

The general form of the Fclose function call is:

Fclose (file pointer);

E.g:

Fclose (fp);

The FCLOSE function returns to 0 when the file is turned off normally. If a non-zero value is returned, there is an error.

13.4 Document read and write to file read and write is the most common file operation. Functions with multiple files read and written in C language:

· Character read and write functions: FGetc and FPUTC

· String read and write functions: Fgets and FPUTS

· Data block read and write functions: freed and fwrite

· Format read and write function: fscanf and fprinf

The following is given separately. Using the above functions requires the header file stdio.h.

13.4.1 Character read and write functions FGETC and FPUTC character read / write functions are read and write functions in character (bytes). Each time you can read or write a character from a file.

1. Read the character function FGETC

The function of the FGetc function is to read a character from the specified file, and the function call is:

Character variable = fgetc (file pointer);

E.g:

CH = FGETC (FP);

Its meaning is to read a character from the open file FP and sent to CH.

With the use of the FGETC function, the following description:

1) In the FGETC function call, the read file must be opened by reading or reading.

2) The result of reading characters can also be assigned to character variables,

E.g:

FGETC (FP);

But the character read the characters cannot be saved.

3) There is a position pointer inside the file. The current read and write byte used to point to the file. When the file is opened, the pointer always points to the first byte of the file. After using the FGETC function, the position pointer will move backward one byte. Therefore, the FGETC function can be used for multiple times, read multiple characters. It should be noted that the file pointer and the location of the file inside the file are not a matter. The file pointer is pointing to the entire file, which must be defined in the program, and the value of the file pointer is unchanged as long as it is not re-assigned. The location pointer inside the file is used to indicate the current read and write location inside the file, each read, the pointer moves backward, it does not need to be defined in the program, but is automatically set by the system.

[Example 13.1] Read file C1.DOC, output on the screen.

#include main ()

{

File * fp;

CHAR CH;

IF ((fp = fopen ("D: //jrzh/example/c1.txt", "r")) == null)

{

Printf ("/ ncannot open file strike any key exit!");

Getch ();

Exit (1);

}

CH = FGETC (FP);

While (ch! = EOF)

{

PUTCHAR (CH);

CH = FGETC (FP);

}

Fclose (fp);

} The functionality of this program is to read characters one by one from the file and display it on the screen. The program defines the file pointer FP to read the text file mode to open the file "D: //jrzh/example//ex1_1.c" and cause the FP to the file. If you open a file error, give a prompt and exit the program. The program 12 first reads a character, and then enter the loop. As long as the character read is not the file end flag (one end flag EOF at each file), the character is displayed on the screen, and then read into the next character. Each read once, the position inside the file indicates a character, and the pointer points to EOF when the file ends. Execute this program will display the entire file.

2. Writing function FPUTC

The function of the FPUTC function is to write a character written to the specified file, the function call is:

FPUTC (word symbol, file pointer);

Among them, the amount of characters to be written can be character constant or variable, for example:

FPUTC ('A', FP);

Its meaning is to write character A to the file pointed to by the FP.

For the use of the FPUTC function, you should also explain the few points:

1) The file written can be opened, read and write, append, and the original file content will be cleared when an existing file is opened by writing or reading and writing, and the writing character starts from the file. If you need to keep the original file content, you want to write the characters to be stored at the end of the file, you must open the file in an additional manner. If the file written does not exist, the file is created.

2) Every word is written, and the internal position of the file will move a byte backward.

3) The FPUTC function has a return value. If the write is successful, the write is returned, otherwise an EOF is returned. This can be used to determine whether the write is successful.

[Example 13.2] Enter a line from the keyboard, write a file, and then read the file content on the screen.

#include

Main ()

{

File * fp;

CHAR CH;

IF ((fp = fopen ("D: // jrzh // example // String", "WT ")) == NULL)

{

Printf ("Cannot Open File Strike Any Key Exit!");

Getch ();

Exit (1);

}

Printf ("INPUT A String: / N");

CH = GetChar ();

While (ch! = '/ n')

{

FPUTC (CH, FP);

CH = GetChar ();

}

Rewind (fp);

CH = FGETC (FP);

While (ch! = EOF)

{

PUTCHAR (CH);

CH = FGETC (FP);

}

Printf ("/ n");

Fclose (fp);

}

The 6th line in the program opens the file string in the read and write text file. Procedure 13th line After reading a character from the keyboard, enter the loop. When the read characters are not a carriage return, the character is written into the file, and then continue to read the next character from the keyboard. For each character, the file internal location points to move one byte backward. After writing, the pointer has pointed to the end of the file. To read the file from the head, you must move the pointer to the file header, and the procedure 19th REWIND function is used to move the internal position pointer of the file finger from the FP to the file header. Rows 20 to 25 are used to read a line of content in the file. [Example 13.3] Distribute the previous file name of the command line parameter, copy it to the file of the latter file name, such as only one file name in the command line, writes the file to the standard output file (display) .

#include

Main (int Argc, char * argv [])

{

File * fp1, * fp2;

CHAR CH;

IF (argc == 1)

{

Printf ("Have Not Enter File Name Strike Any KEY EXIT");

Getch ();

exit (0);

}

IF ((fp1 = fopen (Argv [1], "RT")) == NULL)

{

Printf ("canNot open% S / N", Argv [1]);

Getch ();

Exit (1);

}

IF (argc == 2) fp2 = stdout;

ELSE IF ((fp2 = fopen (argv [2], "wt ")) == null)

{

Printf ("canNot open% S / N", Argv [1]);

Getch ();

Exit (1);

}

While ((ch = fgetc (fp1))! = EOF)

FPUTC (CH, FP2);

Fclose (fp1);

Fclose (fp2);

}

This program is the main function of the belt. Two files fp1 and fp2 are defined in the program, pointing to the files given in the command line parameters, respectively. If the file name is not given in the command line parameter, the prompt information is given. The 18th line of the program means that if only one file name is given, the FP2 points to the standard output file (ie display). The procedure 25 rows to 28 lines of cyclic statements are sent to the file 2 in the read file 1. When running again, a file name is given, so output to the standard output file stdout, which is displayed on the display. The third run, give two file names, so read the contents in the String, write to OK. The DOS command TYPE can be used to display the contents of OK.

13.4.2 String read and write functions Fgets and FPUTS 1. Read string functions FGETS

The function of the function is to read a string into the character array from the specified file, and the function call is:

FGETS (character array name, N, file pointer);

Where N is a positive integer. Indicates that the string read from the file does not exceed N-1 characters. After the last character read, add the string end flag '/ 0'.

E.g:

FGETS (STR, N, FP);

The meaning is to read the N-1 character feeding in the character array STR from the file referred to in the FP.

[Example 13.4] Reads a string containing 10 characters from the string file.

#include

Main ()

{

File * fp;

Char Str [11];

IF ((fp = fopen ("D: // jrzh // example // String", "RT")) == NULL)

{

Printf ("/ ncannot open file strike any key exit!");

Getch ();

Exit (1);

}

FGETS (STR, 11, FP);

Printf ("/ N% S / N", STR);

Fclose (fp);

}

This example defines a total of 11 bytes of a character array STR. After opening the file string in reading a text file, 10 characters are read from the STR array, and will add '/ 0' within the last cell of the array. Then display the output STR array on the screen. The ten characters output is the first ten characters of the Example 13.1 program.

There are two points for the FGETS function:

1) Before reading N-1 characters, if you encounter a chart or EOF, the readout ends.

2) The FGETS function also has a return value whose return value is the first address of the character array.

2. Written string function FPUTS

The function of the FPUTS function is to write a string to the specified file, and its call form is:

FPUTS (string, file pointer);

The string can be a string pattern, or a character number group name, or a pointer variable, for example:

FPUTS ("ABCD", FP);

It is the meaning of writing the string "ABCD" into the file referred to in the FP.

[Example 13.5] Add a string in the file String established in Example 13.2.

#include

Main ()

{

File * fp;

CHAR CH, ST [20];

IF ((fp = fopen ("string", "at ")) == null)

{

Printf ("Cannot Open File Strike Any Key Exit!");

Getch ();

Exit (1);

}

Printf ("INPUT A String: / N");

Scanf ("% s", ST);

FPUTS (ST, FP);

Rewind (fp);

CH = FGETC (FP);

While (ch! = EOF)

{

PUTCHAR (CH);

CH = FGETC (FP);

}

Printf ("/ n");

Fclose (fp);

}

This example requires a string in the String file, so open the file string in the way of the program's sixth line to append writing text files. Then enter the string and write the string into the file string with the FPUTS function. Move the file internal location pointer to the file in the program 15 row. Then enter the cycle one by one to display all the contents in the current file.

13.4.3 Data Block Read and write functions The FREAD and FWTRITE C languages ​​also provide read and write functions for the entire data. Can be used to read and write a set of data, such as an array element, a structural variable value, etc.

The general form of reading data block function call is:

Fread (Buffer, Size, Count, FP);

The general form of writing data block function call is:

FWRITE (Buffer, Size, Count, FP);

among them:

Buffer is a pointer, in the FREAD function, which indicates the first address of the input data. In the fwrite function, it represents the first address of the output data.

Size represents the number of bytes of data blocks.

COUNT indicates the number of data blocks to read and written.

FP represents the file pointer.

E.g:

Fread (FA, 4, 5, FP);

It is the meaning of the FP, and each time you read 4 bytes (a real number) into the real group FA, read 5 times, read 5 real numbers to FA.

[Example 13.6] Enter two student data from the keyboard, write into a file, and read the data of the two student is displayed on the screen.

#include

Struct stu

{

Char Name [10];

Int Num;

Int agec;

CHAR Addr [15];

} Boya [2], Boyb [2], * pp, * QQ; main ()

{

File * fp;

CHAR CH;

INT I;

PP = Boya;

QQ = BOYB;

IF ((fp = fopen ("d: // jrzh // example ///stu_list", "wb ")) == null)

{

Printf ("Cannot Open File Strike Any Key Exit!");

Getch ();

Exit (1);

}

Printf ("/ Ninput Data / N);

For (i = 0; i <2; i , pp )

Scanf ("% s% D% D% S", PP-> Name, & PP-> Num, & PP-> Age, PP-> AddR);

PP = Boya;

FWRITE (PP, SIZEOF (STRUCT STU), 2, FP);

Rewind (fp);

Fread (QQ, SIZEOF (Struct Stu), 2, FP);

Printf ("/ n / nname / tnumber agndr / n");

For (i = 0; i <2; i , qq )

Printf ("% S / T% 5d% 7d% S / N", QQ-> Name, QQ-> Num, QQ-> AGE, QQ-> Addr;

Fclose (fp);

}

This example defines a structural STU that illustrates two structural arrays Boya and Boyb and two structural pointers variables PP and QQ. PP points to BOYA, QQ points to BOYB. Procedure 16th line opens the binary "stu_list" by reading and writing, enters the two student data, write into the file, then move the file internal position pointer to the file, read two student data, on the screen display.

转载请注明原文地址:https://www.9cbs.com/read-33198.html

New Post(0)