In the C language, file operations are done by library functions. The main file manipulation functions are described in this chapter.
File Open function fopen
The fopen function is used to open a file whose invocation is in the general form of a file pointer name =fopen (filename, using file mode) where the "file pointer name" must be a pointer variable that is described as a file type, and "file name" is the file name of the files being opened. "Use file Mode" refers to the type of file and the operational requirements. "File name" is a string constant or an array of strings. For example: File *fp; fp= ("File A", "R"); The meaning is to open file A in the current directory, only allow "read" operation, and make FP point to the file. Another example: File *fphzk fphzk= ("C:\\hzk16", "RB") its meaning is to open the C drive disk root directory of the files hzk16, this is a binary file, only allowed to read in binary mode. The first of the two backslashes "\ \" represents an escape character, and the second represents the root directory. There are 12 ways to use the file, and the symbols and meanings are given below.
File usage means "RT"
Read-only open a text file, allowing only read data "WT"
Write only open or create a text file, only allow write data "at"
Append open a text file and write data at the end of the file "RB"
Read-only open a binary file, allowing only read data "WB"
Write only open or create a binary file, only allow write data "AB"
Append open a binary file and write data "rt+" at the end of the file
Read and write open a text file, allowing read and write "wt+"
Read-write open or create a text file that allows read and write "at+"
Read/write open a text file, allow reading, or append data "rb+" at the end of the file
Read and write open a binary file that allows read and write "wb+"
Read-write open or create a binary file that allows reading and writing "ab+"
Read and write open a binary file, allow reading, or append data at the end of the file
There are several explanations for how the file is used:
1. File usage by r,w,a,t,b,+ Six characters, the meaning of each character is: R (Read): Read W (write): Writes a (append): Append t: Text file, can be omitted do not write B (banary): binary file +: Read and Write
2. When a file is opened with "R", the file must already exist and can only be read from the file.
3. Files opened with "W" can only be written to the file. If the open file does not exist, the file is created with the specified file name, and if the open file already exists, the file is deleted and a new file is rebuilt.
4. To append new information to an existing file, you can only open the file in "a" mode. However, the file must be present at this point, or an error will occur.
5. If an error occurs when opening a file, fopen will return a null pointer value of NULL. In the program can use this information to determine whether to complete the work of open files, and corresponding processing. Therefore, the following procedure is often used to open the file: 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, indicating that the hzk16 file under the C packing directory cannot be opened, the message "Error on open C: \ hzk16file!" is given, and the next line of Getch () is to enter a character from the keyboard but not on the screen. Here, the function of the line is to wait, and the program will continue to execute only when the user taps any key from the keyboard, so the user can use this wait time to read the error prompt. Execute exit (1) to exit the program after tapping the key.
6. When a text file is read into memory, the ASCII code is converted to binary code, and the file is written in text to the disk, the binary code is converted to ASCII code, so the text file read and write to spend more time to convert. There is no such conversion to read and write binary files.
7. Standard input file (keyboard), standard output file (display), standard error output (Error message) is open by the system, can be used directly. File Close function fclose file once used, the closed file function is applied to close the file to avoid errors such as data loss of the file.
fclose function
The general form of invocation is: fclose (file pointer); For example: fclose (FP); When the close file operation is completed normally, the Fclose function returns a value of 0. Returning a value other than 0 indicates an error occurred. Read and write files are the most commonly used file operations.
There are several functions for reading and writing files in the C language: • Character reading and writing functions: Fgetc and FPUTC string read and write functions: Fgets and fputs data block read and write functions: Freed and fwrite formatted read-write functions: fscanf and Fprinf
The following are presented separately. Using the above functions requires the inclusion of the header file stdio.h. character reading and writing functions fgetc and FPUTC character reading and writing functions are read and write functions in characters (bytes). Each time a character can be read from a file or written to a file.
One, read character function fgetc
The function of the FGETC function is to read a character from the specified file, in the form of a function call: a character variable =fgetc (file pointer); For example: Ch=fgetc (FP); The meaning is to read a character from an open file FP and feed it into ch.
There are several explanations for the use of the FGETC function: 1. In the FGETC function call, the read file must be opened in read or read-write mode.
2. The result of reading a character can also not assign a value to a character variable, for example: fgetc (FP), but the read-out character cannot be saved.
3. There is a position pointer inside the file. The current read and write bytes used to point to the file. When the file is opened, the pointer always points to the first byte of the file. When you use the FGETC function, the position pointer moves backwards by one byte. Therefore, multiple characters can be read by using the FGETC function multiple times in succession. Note that file pointers and positional pointers inside files are not the same thing. The file pointer is to the entire file, you must define the description in the program, as long as you do not reassign the value, the value of the file pointer is constant. The position pointer inside the file indicates the current read and write location inside the file, each time it is read and written, the pointer moves backwards, it does not need to define the description in the program, but is automatically set by the system.
[Example 10.1] read the file e10-1.c, output on the screen. #include <stdio.h> main () {file *fp; char ch; if (Fp=fopen ("e10_1.c", "RT") ==null) {printf ("Cannot open FILE strike Any key exit! "); Getch (); Exit (1); } ch=fgetc (FP); while (ch!=eof) {putchar (ch); ch=fgetc (FP);} fclose (FP); The function of this program is to read the characters from the file and display them on the screen. The program defines the file pointer fp, opens the file "e10_1.c" as a read text file, and makes the FP point to the file. If there is an error opening the file, give the prompt and exit the program. The 12th line of the program reads a character and then enters the loop, as long as the read character is not the end-of-file flag (at the end of each file, EOF) displays the character on the screen and then reads the next character. Every time you read, the position pointer inside the file moves backwards by one character, and when the file ends, the pointer points to EOF. Executing this program will display the entire file.
Second, the character function fputc
The function of the FPUTC function is to write a character to the specified file, in the form of a function call: FPUTC (character amount, file pointer), where the amount of characters to be written can be a character constant or a variable, for example: FPUTC (' a ', FP), meaning that the character A is written to the file pointed to by the FP.
The use of the FPUTC function is also to illustrate several points: 1. The written file can be used, written, read and write, appended to open, write or read to open an existing file will clear the original file content, write characters from the beginning of the file. To keep the contents of the original file, you want to write the characters to start at the end of the file, you must open the file in Append mode. The file that was written to does not exist, it is created.
2. Each write one character, the internal position of the file pointer moves backwards one byte.
3. The FPUTC function has a return value, such as if the write succeeds, returns a written character, or an EOF is returned. You can use this to determine if the write was successful.
[Example 10.2] input a line of characters from the keyboard, write a file, and then read out the contents of the file displayed on the screen. #include <stdio.h> main () {file *fp; char ch; if (Fp=fopen ("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 of the program opens a file string as a read-write text file. The 13th line of the program reads a character from the keyboard into a loop, and when the read-in character is not a carriage return, the character is written to the file, and then the next character is read from the keyboard. Each character is entered, and the internal position pointer moves backwards by one byte. After writing, the pointer is pointing to the end of the file. If you want to read the file from the beginning, you need to move the pointer to the file header, the 19th line of the program Rewind function is used to move the internal position of the FP file pointer to the file header. Line 20th to 25th is used to read a line in the file.
[Example 10.3] The file that identifies the previous file name in the command line argument is copied to the file that is identified by the latter file name, such as only one file name in the command line that writes the file to a standard output file (display). #include <stdio.h> main (int Argc,char *argv[]) {file *fp1,*fp2; char ch; if (argc==1) {printf ("has not enter FILE N Ame 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 procedure is the main function with parameters. The program defines two file pointers, FP1 and FP2, pointing to the files given in the command line arguments. If the file name is not given in the command line arguments, a prompt is given. The 18th line of the program indicates that if only one file name is given, FP2 points to the standard output file (that is, the monitor). Lines 25th to 28 of the program are read out of the characters in file 1 and sent to file 2 with a looping statement. When running again, a file name (created by example 10.2) is given, so output to the standard output file stdout, which displays the contents of the file on the display. The third run, which gives two file names, reads the contents of the string and writes it to OK. The DOS command type displays the contents of OK: string read-write function fgets and fputs
The function of reading a string function Fgets function is to read a string into a character array from the specified file, in the form of a function call: fgets (character array name, n, file pointer), where n is a positive integer. Indicates that a string that is read from a file does not exceed n-1 characters. After the last character read, add the string end flag ' \ s '. For example: Fgets (STR,N,FP), the meaning is to read from the file referred to in the FP n-1 characters into the character array str. [Example 10.4] reads a string containing 10 characters from the e10_1.c file. #include <stdio.h> main () {file *fp; char str[11]; if ((Fp=fopen ("e10_1.c", "RT") ==null) {printf ("Cannot open FILE s Trike any key exit! "); Getch (); Exit (1); } fgets (STR,11,FP); printf ("%s", str); Fclose (FP); } This example defines a character array str total of 11 bytes, after opening the file e101.c as a read text file, read out 10 characters into the STR array, in the last cell of the array will be added ' \ ', and then display the output str array on the screen. The output of the 10 characters is exactly the first 10 characters of the example 10.1 program.
The Fgets function has a two-point description: 1. Before the n-1 characters are read out, if a newline character or EOF is encountered, the end of the readout is completed. 2. The Fgets function also has a return value whose return value is the first address of a character array.
Second, write String function fputs
The function of the fputs function is to write a string to the specified file in the form of: fputs (string, file pointer) where the string can be a string constant, or it can be a character array name, or a pointer variable, for example: Fputs ("ABCD", FP); its meaning is to put the string "ABCD "writes to the file referred to in the FP. [Example 10.5] appends a string to the file created in Example 10.2. #include <stdio.h> main () {FILE *fp; char ch,st[20]; if ((Fp=fopen ("string", "at+") ==null) {printf ("Cannot open fil E 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 the string to be written at the end of the string file, so the file string is opened in line 6th of the program to append a read-write text file. It then enters a string and writes it to the file string using the Fputs function. In program 15, use the rewind function to move the file's internal position pointer to the top of the file. Then enter the loop to display the entire contents of the current file one by one.
Data block read-write function fread and fwrite
The C language also provides read and write functions for the entire block of data. can be used to read and write a set of data, such as an array element, the value of a struct variable, and so on. The general form of a read block function call is: fread (BUFFER,SIZE,COUNT,FP); The general form of a write block function call is: fwrite (BUFFER,SIZE,COUNT,FP); Where buffer is a pointer, in the Fread function, it represents the first address that holds the input data. In the Fwrite function, it represents the first address that holds the output data. size represents the number of bytes of data block. count represents the number of blocks of data block to read and write. fp represents a file pointer. For example: Fread (FA,4,5,FP); The meaning is from the file referred to in the FP, each read 4 bytes (a real number) into the real group FA, read 5 consecutive times, that is, read 5 real numbers into FA. [Example 10.6] from the keyboard input two student data, write a file, read out the data of the two students displayed on the screen. #include <stdio.h> struct stu {char name[10]; int num; int age; char addr[15];} BOYA[2],BOYB[2],*PP,*QQ; Main () {file *fp; char ch; int i; Pp=boya; qq=boyb; if (Fp=fopen ("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 age addr\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 structure Stu, describes two arrays of structures Boya and &NBSP;BOYB, and two structure pointer variables pp and QQ. PP pointing boya,qq to Boyb. The program line 16th reads and writes the binary file "Stu_list", enters two student data, writes to the file, then moves the file internal position pointer to the top of the file, reads out two student data, displays on the screen.
Format read-write functions fscanf and fprintf
The FSCANF function, the fprintf function, is similar to the function of the scanf and printf functions used earlier, and is a formatted read-write function. The difference between is that the read and write objects of the fscanf function and the fprintf function are not keyboards and monitors, but disk files. The invocation formats for these two functions are: fscanf (file pointer, format string, Input table column), fprintf (file pointer, format string, output table column); For example: fscanf (FP, "%d%s", &i,s); fprintf (FP, "%d%c", J,ch); with fscanf and fprintf functions can also complete the problem of example 10.6. The modified program is shown in example 10.7. [Example 10.7] #include <stdio.h> struct stu {char name[10]; int num; int age; char addr[15];} BOYA[2],BOYB[2],*PP,*QQ; Main () {file *fp; char ch; int i; Pp=boya; qq=boyb; if (Fp=fopen ("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; for (i=0;i<2;i++,pp++) fprintf (FP, "%s %d %d %s\n",pp->name,pp->num,pp->age,pp-> addr); Rewind (FP); for (i=0;i<2;i++,qq++) fscanf (FP, "%s %d %d %s\n", QQ->NAME,&QQ->NUM,&QQ->AGE,QQ->ADDR); printf ("\n\nname\tnumber age addr\n"); Qq=boyb; for (i=0;i<2;i++,qq++) printf ("%s\t%5d %7d %s\n", Qq->name,qq->num, qq->age, qq-> addr); Fclose (FP); Compared to example 10.6, the FSCANF and fprintf functions in this program can read and write only one structure array element at a time, so a looping statement is used to read and write all the array elements. Also note that the pointer variable pp,qq because the loop changes their values, so in the program's 25 and 32 rows they are re-assigned to the array's first address.
A/C + + file operation 1