Using feof( ) function

The function feof() determines whether the end of the file has been encountered. The feof() function has prototype:

int feof(FILE *fp);

feof() returns true(1) if the end if the file has been reached; otherwise, it returns 0.




The operation of feof() is illustrated in the example 3.

String input/output function in file

Reading or writing strings of characters from and to files is easy as reading and writing individual characters. fputs() and fgets() are string(line) input/output function in C.

The fputs() function writes the string pointed by string variable to the specified stream. It returns EOF if an error occurs. Since fputs() does not automatically add a new line character to the end if the string; we must do this explicitly to read the string back from the file.

The fgets() function reads a string from the specified stream until either a new line character is read or length-1 character have been read. The function fgets() takes three arguments: the first is the address where the string is stored, the second is the maximum length of the string, and the third is the pointer to the structure FILE. When all the lines from the file have been read, if we attempt to read one more times it will return NULL.

Here is a sample program that writes strings to a file using the function fputs() and reads string from the file using fgets() function.

Example 3:







char string[25];

FILE *fp;




puts(“Cannot open file “);





printf(“Enter a string to store in data file :”);


strcat(string,”\n”); /*add a new line ,since fgets() does not automatically add new line character to the end of the string */






fgets(string ,25,fp);






In this example, while writing to a data file do-while loop is used, this allows you to enter any number of strings. To stop entering you have to press enter at the beginning (i.e. new line character should appear at the beginning). Similarly strings can be read from the data file until the end-of-line is reached.

Method of copying the content of one file to another (Prev Lesson)
(Next Lesson) Using rewind ( ) function
Back to C-Programming

No Comments

Post a Reply

Bhim Gautam
Role : Lecturer
Read More
error: Content is protected !!