To access and use a file stored on disk, it must first be opened and associated with a special file variable. When a file is opened, the operating system gives your program access to the file for reading or writing data.
Opening a File
A file is opened using the fopen
function:
filevar = fopen(filename, mode);
which requires two arguments, the name of the file to be opened and the mode of access:
- filename - a string containing the name of the file to open. The name can include a relative or absolute path name.
- mode - a string that specifies how the file will be accessed. A file can be opened in one of three modes:
"r"
- opens the file for reading
"w"
- opens the file for writing
"a"
- opens the file for appending new data
The function returns a pointer to an internal file structure. This pointer, which has to be assigned to a FILE
pointer variable, is then used with other file related functions to access the file. Here, we use the variable infile
for the input file and outfile
for the output file
FILE *infile;
FILE *outfile;
and open two files, one for reading and one for writing
infile = fopen("records.txt", "r");
outfile = fopen("report.txt", "w");
A file opened for reading must exist and the program must have read access to the file. If a file is opened for writing a new file is always created; an existing file with the same name will be erased. The program must have read and write access to the directory in which the new file will be created. Opening a file for appending is similar to writing, with the exception that if the file exists, it is not erased. Instead, new data is appended to the end of the existing file.
Question 1
Consider each of the following code segments which contains at least one error, syntax, logical, or both. Explain the problem with each code segment.
-
FILE *infile = fopen("data.txt");
The fopen
function requires two arguments, the name of the file and the mode. The operating system must know whether you want to use the file for reading or writing. Thus, the second argument is required and it must be either "r"
or "w"
.
-
The fopen
function returns a pointer to an internal file structure that is needed to reference the file later in the program. The return value must be assigned to a variable of type FILE *
.
Closing Files
When you have finished using the file, it should be closed, which is done by calling the fclose
function and passing the file appropriate file pointer
fclose(infile);
fclose(outfile);
By closing the file, the system will release internal buffers that were created for storing the data as it was read to or written from the file. A file cannot be accessed again after it has been closed, until it unless it is first reopened.