Page 142 - 6437
P. 142
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in
/tmp directory and writes two lines using two different functions. Let us read this file in
the next section.
Reading a File
Given below is the simplest function to read a single character from a file:
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return
value is the character read, or in case of any error, it returns EOF. The following function allows
to read a string from a stream:
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp.
It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they
have read the maximum number of characters, then it returns only the characters read up to that
point including the new line character. You can also use int fscanf(FILE *fp, const char
*format, ...) function to read strings from a file, but it stops reading after encountering the first
space character.
#include <stdio.h>
main()
{
FILE *fp;
char buff[255];
145