Sams Teach Yourself C in 21 Days

(singke) #1
Listing 16.7 demonstrates the use of feof(). When you’re prompted for a filename, enter
the name of any text file—one of your C source files, for example, or a header file such
as stdio.h. Just be sure that the file is in the current directory, or else enter a path as part
of the filename. The program reads the file one line at a time, displaying each line on
stdout, untilfeof()detects end-of-file.

LISTING16.7 feof.c. Using feof()to detect the end of a file
1: /* Detecting end-of-file. */
2: #include <stdlib.h>
3: #include <stdio.h>
4:
5: #define BUFSIZE 100
6:
7: int main( void )
8: {
9: char buf[BUFSIZE];
10: char filename[60];
11: FILE *fp;
12:
13: puts(“Enter name of text file to display: “);
14: gets(filename);
15:
16: /* Open the file for reading. */
17: if ( (fp = fopen(filename, “r”)) == NULL)
18: {
19: fprintf(stderr, “Error opening file.”);
20: exit(1);
21: }
22:
23: /* If end of file not reached, read a line and display it. */
24:
25: while ( !feof(fp) )
26: {
27: fgets(buf, BUFSIZE, fp);
28: printf(“%s”,buf);
29: }
30:
31: fclose(fp);
32: return 0;
33: }

Enter name of text file to display:
hello.c
#include <stdio.h>
int main( void )
{
printf(“Hello, world.”);
return(0);
}

464 Day 16

INPUT

INPUT/
OUTPUT

26 448201x-CH16 8/13/02 11:13 AM Page 464

Free download pdf