Sams Teach Yourself C in 21 Days

(singke) #1
main()in Listing 16.10 should look very familiar. It’s nearly identical to the main()in
Listing 16.9, with the exception of line 14. Instead of rename(), this function uses
copy(). Because C doesn’t have a copy function, lines 24 through 60 create a copy func-
tion. Lines 31 and 32 open the source file,fold, in binary read mode. Lines 36 through
40 open the destination file,fnew, in binary write mode. Notice that line 38 closes the
source file if there is an error opening the destination file. The whileloop in lines 46
through 54 does the actual copying of the file. Line 48 gets a character from the source
file,fold. Line 50 checks to see whether the end-of-file marker was read. If the end of
the file has been reached, a breakstatement is executed in order to get out of the while
loop. If the end of the file has not been reached, the character is written to the destination
file,fnew. Lines 56 and 57 close the two files before returning to main().

Using Temporary Files ......................................................................................


Some programs make use of one or more temporary files during execution. A temporary
file is a file that is created by the program, used for some purpose during program execu-
tion, and then deleted before the program terminates. When you create a temporary file,
you don’t really care what its name is, because it gets deleted. All that is necessary is that
you use a name that isn’t already in use for another file. The C standard library includes
a function tmpnam()that creates a valid filename that doesn’t conflict with any existing
file. Its prototype in stdio.h is as follows:
char *tmpnam(char *s);
The argument smust be a pointer to a buffer large enough to hold the filename. You can
also pass a null pointer (NULL), in which case the temporary name is stored in a buffer
internal to tmpnam(), and the function returns a pointer to that buffer. Listing 16.11
demonstrates both methods of using tmpnam()to create temporary filenames.

LISTING16.11 tempname.c. Using tmpnam()to create temporary filenames
1: /* Demonstration of temporary filenames. */
2:
3: #include <stdio.h>
4:
5: int main( void )
6: {
7: char buffer[10], *c;
8:
9: /* Get a temporary name in the defined buffer. */
10:
11: tmpnam(buffer);
12:

470 Day 16

INPUT

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

Free download pdf