Programming in C

(Barry) #1
I/O Functions 475

FILE *fopen (fileName, accessMode)
Opens the specified file with the indicated access mode.Valid modes are "r"for read-
ing,"w"for writing,"a"for appending to the end of an existing file,"r+"for
read/write access starting at the beginning of an existing file,"w+"for read/write
access (and the previous contents of the file, if it exists, are lost), and "a+"for
read/write access with all writes going to the end of the file. If the file to be opened
does not exist, it is created if the accessModeis write ("w","w+") or append ("a",
"a+"). If a file is opened in append mode ("a"or "a+"), it is not possible to overwrite
existing data in the file.
On systems that distinguish binary from text files, the letter bmust be appended to
the access mode (as in "rb") to open a binary file.
If the fopencall is successful, a FILEpointer is returned to be used to identify the file
in subsequent I/O operations; otherwise, a null pointer is returned.
int fprintf (filePtr, format, arg1, arg2, ..., argn)
Writes the specified arguments to the file identified by filePtr, according to the for-
mat specified by the character string format.Format characters are the same as for
the printffunction (see Chapter 16, “Input and Output Operations in C”).The
number of characters written is returned. A negative return value indicates that an
error occurred on output.
int fputc (c, filePtr)
Writes the value of c(converted to an unsigned char) to the file identified by
filePtr,returning cif the write is successful, and the value EOFotherwise.
int fputs (buffer, filePtr)
Writes the characters in the array pointed to by bufferto the indicated file until the
terminating null character in bufferis reached. A newline character is notautomati-
cally written to the file by this function. On failure, the value EOFis returned.
size_t fread (buffer, size, n, filePtr)
Reads nitems of data from the identified file into buffer. Each item of data is size
bytes in length. For example, the call
numread = fread (text, sizeof (char), 80, in_file);
reads 80 characters from the file identified by in_fileand stores them into the array
pointed to by text.The function returns the number of data items successfully read.
FILE *freopen (fileName, accessMode, filePtr)
Closes the file associated with filePtrand opens the file fileNamewith the speci-
fied accessMode(see the fopenfunction).The file that is opened is subsequently

21 0672326663 AppB 6/10/04 2:03 PM Page 475

Free download pdf