Sams Teach Yourself C in 21 Days

(singke) #1
Using Disk Files 469

16


27: int c;
28:
29: /* Open the source file for reading in binary mode. */
30:
31: if ( ( fold = fopen( oldname, “rb” ) ) == NULL )
32: return -1;
33:
34: /* Open the destination file for writing in binary mode. */
35:
36: if ( ( fnew = fopen( newname, “wb” ) ) == NULL )
37: {
38: fclose ( fold );
39: return -1;
40: }
41:
42: /* Read one byte at a time from the source; if end of file */
43: /* has not been reached, write the byte to the */
44: /* destination. */
45:
46: while (1)
47: {
48: c = fgetc( fold );
49:
50: if ( !feof( fold ) )
51: fputc( c, fnew );
52: else
53: break;
54: }
55:
56: fclose ( fnew );
57: fclose ( fold );
58:
59: return 0;
60: }

Enter source file: list1610.c
Enter destination file: tmpfile.c
Copy operation successful
The function copy_file()works perfectly well, letting you copy anything from
a small text file to a huge program file. It does have limitations, however. If the
destination file already exists, the function deletes it without asking. A good program-
ming exercise for you is to modify copy_file()to check whether the destination file
already exists, and then query the user as to whether the old file should be overwritten.

LISTING16.10 continued

INPUT/
OUTPUT

ANALYSIS

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

Free download pdf