Why programs need files
Earlier programs stored input in variables or arrays in runtime memory. After the program ends, running it again does not automatically restore those values. To keep scores, orders, or settings for later use, we need to write data to a file.
A file is a collection of data managed by the operating system, usually stored on a disk or another storage device. Its name and path help us locate it. A text file can be processed as characters, such as a line containing a name and a score; a program can read those characters without asking a person to type them again.
“Opening a file” does not mean opening a window
Double-clicking a desktop file usually asks an editor or another application to display it. Calling fopen in C does not pop up a window. It uses a path and an opening mode to request a channel through which the program can access the file.
Think of the sequence as finding the file and obtaining an access channel, reading or writing through that channel, and then ending this access. Opening successfully does not mean all the contents have been read or copied into a variable.
C calls this channel a stream. The standard library uses FILE to manage stream state, such as its current position, read/write status, and buffering information. The FILE * returned by fopen points to that management object, not to the first character of the file. Dereferencing it is not how we read file characters.
Open, check, then close
In fopen("file-io-sample.txt", "r"), the first argument identifies the file and "r" requests read-only access to an existing file. Success returns a stream pointer; a missing path or insufficient permissions can cause failure, which returns NULL. Check first: do not pass a failed, null result to reading, writing, or closing functions.
For now, we will establish and end access without reading the contents.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("file-io-sample.txt", "r");
if (fp == NULL) {
fprintf(stderr, "Cannot open file-io-sample.txt.\n");
return 1;
}
if (fclose(fp) != 0) {
fprintf(stderr, "Cannot close the file.\n");
return 1;
}
return 0;
}fprintf(stderr, "..."); writes the specified message to the standard error stream. For now, think of it as displaying an error message. stderr is provided by <stdio.h>, usually appears in the terminal, and does not need to be opened or closed by us. These messages are written by the programmer; they do not automatically explain the operating system's specific error.
fclose(fp) ends access through this stream and releases its associated resources. If output remains in a buffer, it also attempts to write that output out. It does not close a screen window or delete the file. Our read-only example has no pending output.
A return value of 0 means closing succeeded; a nonzero value means an error occurred. After calling it, do not read or write through the stream pointer or close it again. Even if it reports an error, report that error instead of retrying the close. To access the file later, call fopen again to obtain a new stream.
Prepare the sample file
A relative path starts from the program's current working directory, not necessarily the source file's directory. Before running the examples, create file-io-sample.txt in that directory by copying this text:
Leaflet file I/O sample
The second line is ready to read.Text file open modes
| Mode | Read | Write | If missing | If present | Initial position |
|---|---|---|---|---|---|
r | Yes | No | Fail | Preserve | Beginning |
w | No | Yes | Create | Truncate | Beginning |
a | No | Yes | Create | Preserve; writes append | Implementation-defined beginning or end; writes always go to end |
r+ | Yes | Yes | Fail | Preserve | Beginning |
w+ | Yes | Yes | Create | Truncate | Beginning |
a+ | Yes | Yes | Create | Preserve; writes append | Read position is implementation-defined; writes go to end |
w and w+ immediately truncate an existing file. The + means both reading and writing are allowed; it does not mean append.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Safely check and close the sample file
Copy the text shown in this lesson to create file-io-sample.txt, then open it in r mode. On failure, use fprintf(stderr, ...) to report the error and return 1. On success, print “opened,” check fclose, and return 0. Do not read the contents yet.
- Call fopen("file-io-sample.txt", "r").
- If it returns NULL, report the error and stop.
- On success, print confirmation and check that fclose returns 0.