Solution for Exercise 22-2
ex2202
#include <stdio.h> #include <stdlib.h> int main() { FILE *fh; int ch; /* open the file */ fh=fopen("hello.txt","r"); /* check for errors */ if(fh==NULL) { puts("Can't open that file!"); exit(1); } /* loop until the end-of-file */ while( !feof(fh) ) { /* read one character */ ch=fgetc(fh); /* end of file? */ if( ch==EOF ) break; /* output character */ putchar(ch); } /* close the file */ fclose(fh); return(0); }
Output
Look what I made!
Notes
* This code assumes the file hello.txt
exists in the same directory where the program is run. The output assumes the file's content as well.
* If you don't use the if test in the while loop (at Line 23), the EOF "character" is output, which adds an extra blank character to the output on most systems.
* Another way to write the while loop is like this:
The expression ch=getch(fh)
must be enclosed in parentheses to prevent it from being evaluated directly. Inside the parentheses, its return value is compared as an int with the EOF
constant.
Copyright © 1997-2024 by QPBC.
All rights reserved