Programming in C

(Barry) #1
Exercises 371

exitcall terminates the program immediatelywhereas returnsimply transfers control
back to the calling routine.


Renaming and Removing Files


The renamefunction from the library can be used to change the name of a file. It takes
two arguments: the old filename and the new filename. If for some reason the renaming
operation fails (for example, if the first file doesn’t exist, or the system doesn’t allow you
to rename the particular file),renamereturns a nonzero value.The code


if ( rename ("tempfile", "database") ) {
fprintf (stderr, "Can't rename tempfile\n");
exit (EXIT_FAILURE);
}


renames the file called tempfileto databaseand checks the result of the operation to
ensure it succeeded.
The removefunction deletes the file specified by its argument. It returns a nonzero
value if the file removal fails.The code


if ( remove ("tempfile") )
{
fprintf (stderr, "Can't remove tempfile\n");
exit (EXIT_FAILURE);
}


attempts to remove the file tempfileand writes an error message to standard error and
exit if the removal fails.
Incidentally, you might be interested in using the perrorfunction to report errors
from standard library routines. For more details, consult Appendix B.
This concludes our discussion of I/O operations under C. As mentioned, not all of
the library functions are covered here due to lack of space.The standard C library con-
tains a wide selection of functions for performing operations with character strings, for
randomI/O, mathematical calculations, and dynamic memory management. Appendix B
lists many of the functions inside this library.


Exercises



  1. Type in and run the three programs presented in this chapter. Compare the output
    produced by each program with the output presented in the text.

  2. Go back to programs developed earlier in this book and experiment with redirect-
    ing their input and output to files.

  3. Write a program to copy one file to another, replacing all lowercase characters
    with their uppercase equivalents.

Free download pdf