In the previous section, Example 2, the program reads characters from one file and outputs them to the screen, with EOF as the end of the file in the while loop. This file with EOF as the end-of-file flag must be a text file. In a text file, data is stored in the form of ASCII values of characters. We know that the ASCII value range is 0~255, it is not possible to 1, so you can use EOF as a flag to end the file.
When data is stored in binary form in a file, there is a value of 1, which cannot be used as the end flag of a binary file. To solve this problem, ANSI C provides a feof function to determine whether the file is finished. If the end of the file is encountered, the value of the function feof (FP) is 1, otherwise 0. The feof function can be used to determine whether a binary file is finished or not, or whether the text file ends.
Example 1 a program for copying a text file (source file) to another file (the destination file). The source file name is File_a.dat and the target file name is File_b.dat.
The procedure is as follows:
1#include <stdio.h>2#include <stdlib.h>3 4 //declaring file copy functions5 voidFileCopy (file *fpin, file *fpout);6 7 intMain ()8 {9FILE *fpin, *fpout;Ten OneFpin = fopen ("D:\\test\\file_a.dat","R");//Open Input File A if(Fpin = =NULL) - { -printf"Can ' t open this file!\n"); theExit0);//using the Exit function, you must include the Stdlib.h header file - } - -Fpout = fopen ("D:\\test\\file_b.dat","W");//Open Output File + -FileCopy (Fpin, fpout);//file Copy + A //close input, output file at fclose (fpin); - fclose (fpout); - return 0; - } - - //defining the FileCopy function in voidFileCopy (file *fpin, file *fpout) - { to Charch; +ch = getc (Fpin);//read a character first, and use the feof function to determine whether it is an empty file - //A function feof (FP) value of 1 is encountered when the file end flag is met, otherwise 0 the while(!feof (fpin)) * { $ PUTC (CH, fpout);Panax Notoginsengch = getc (Fpin);//Copy by character - } the}
View Code
Source file:
Target file:
Determine end of file function feof