Text File Functions in C Programming Language

When working with text files, C provides four functions which make file operations easier. The first two are called fputs() and fgets(), which write or read a string from a file, respectively. 

Their prototypes are:

int fputs(char *str,FILE *fp);

char *fgets(char *str, int num, FILE *fp);

The fputs() function writes the string pointed to by str to the file associated with fp. It returns EOF if an error occurs and a non-negative value if successful. The null that terminates str is not written and it does not automatically append a carriage return/linefeed sequence.

The fget() function reads characters from the file associated with fp into a string pointed to by str until num-1 characters have been read, a new line character is encountered, or the end of the file is reached. The string is null-terminated and the new line character is retained. The function returns str if successful and a null pointer if an error occurs.
The other two file handling functions to be covered are fprintf() and fscanf(). These functions operate exactly like printf() and scanf() except that they work with files. Their prototypes are:

int fprintf(FILE *fp, char *control-string, ...);

int fscanf(FILE *fp, char *control-string ...);

Instead of directing their I/O operations to the console, these functions operate on the file specified by fp. Otherwise their operations are the same as their console-based relatives. The advantages to fprintf() andfscanf() is that they make it very easy to write a wide variety of data to a file using a text format.


Learn More :