Programming in C

(Barry) #1
Special Functions for Working with Files 367

while ( (c = getc (in)) != EOF )
putc (c, out);

// Close open files

fclose (in);
fclose (out);

printf ("File has been copied.\n");

return 0;
}


Program 16.3 Output


Enter name of file to be copied: copyme
Enter name of output file: here
File has been copied.


Now examine the contents of the file here.The file should contain the same three lines
of text as contained in the copymefile.
The scanffunction call in the beginning of the program is given a field-width count
of 63 just to ensure that you don’t overflow your inNameor outNamecharacter arrays.
The program then opens the specified input file for reading and the specified output file
for writing. If the output file already exists and is opened in write mode, its previous
contents are overwritten on most systems.
If either of the two fopencalls is unsuccessful, the program displays an appropriate
message at the terminal and proceeds no further, returning a nonzero exit status to indi-
cate the failure. Otherwise, if both opens succeed, the file is copied one character at a
time by means of successive getcand putccalls until the end of the file is encountered.
The program then closes the two files and returns a zero exit status to indicate success.


The feofFunction


To test for an end-of-file condition on a file, the function feofis provided.The single
argument to the function is a FILEpointer.The function returns an integer value that is
nonzero if an attempt has been made to read past the end of a file, and is zero otherwise.
So, the statements


if ( feof (inFile) ) {
printf ("Ran out of data.\n");
return 1;
}


Program 16.3 Continued

Free download pdf