File Streams in C: Open, Read, Write, and Close
A file stream is a C library abstraction through which your program reads characters from, or writes characters to, a file. You use file streams in C when loading settings, processing text records, or saving reports. The library manages the connection and its state; your program chooses an appropriate mode and checks whether each operation succeeds.
Open the connection deliberately
The function fopen returns a FILE * on success and NULL on failure. The filename identifies the file; the mode specifies the permitted operation and what happens to existing contents.
Mode | Permitted operation | Existing file | Missing file |
|---|---|---|---|
"r" | Read | Contents preserved | Opening fails |
"w" | Write | Contents discarded on successful opening | Creation attempted |
"a" | Append | Contents preserved; writes go at the end | Creation attempted |
Creation can still fail, for example because the containing directory does not permit writing. Check the returned pointer before using the stream.
The following fragments belong inside a function and assume the standard header stdio.h has been included.
FILE *in = fopen("readings.txt", "r");
if (in == NULL) {
/* Report the opening failure. */
return 1;
}Read chunks without overrunning the array
A buffer is an area of memory used to hold data temporarily. For fgets, you supply a character array and its capacity. With capacity n, the maximum number of input characters stored by a successful call is
The remaining position allows a terminating null character, written '\0'. This added character is not read from the file.
fgets stops after storing a newline, filling the available input capacity, or encountering end-of-file. A newline that fits is retained. Therefore, one successful call does not necessarily read one complete line. Long lines arrive in multiple chunks.
Example: With char buf[9], a successful fgets(buf, sizeof buf, in) stores at most eight input characters, followed by '\0'.
Use the return value to decide whether the array contains newly read data:
char buf[80];
while (fgets(buf, sizeof buf, in) != NULL) {
/* Process the successfully read chunk. */
}
if (ferror(in)) {
/* Report a read error. */
}A null return can indicate end-of-file before any characters were read or a read error. ferror tests the error indicator; feof tests the end-of-file indicator. These indicators describe conditions already detected by an operation. Testing feof before reading does not predict whether the next read will succeed.
Write text and finish the stream
fprintf sends formatted text to a chosen stream. For example, fprintf(out, "%d\n", count) writes an integer followed by a newline. Its successful return value counts output characters; a negative return reports an output error. It does not write a string terminator after the formatted text.
The library may hold output temporarily in its own internal storage. This buffering is separate from the array you pass to fgets. Consequently, a positive fprintf result does not establish that closing the stream will succeed.
Call fclose once when finished with each successfully opened stream. Closing flushes pending output and releases stream resources. Its return is zero on success or EOF on failure. Do not use the stream again after closing, even if closing reported failure.
What to remember
- Choose "r", "w", or "a" according to the required treatment of existing contents.
- Let successful reads control processing, and reserve space for '\0'.
- Check error indicators when reading stops and check the result of closing.
Example: Audit a Wildlife Observation File
A wildlife station stores observations in a Unix text file containing exactly owl\nbadger\n, where each \n represents one newline. Every letter and newline occupies one byte, and there are no embedded null characters. You will read the file and append a summary to audit.txt, preserving any previous summaries. A chunk here means the input characters returned by one successful fgets call.
Assume all opening, reading, writing, and closing operations succeed. The fragments below run inside a function with stdio.h and string.h already included.
a) Choose the opening modes for observations.txt and audit.txt, and explain the checks needed before using either stream.
Open the observations for reading and the audit file for appending:
FILE *in = fopen("observations.txt", "r");
if (in == NULL) {
return 1;
}
FILE *log = fopen("audit.txt", "a");
if (log == NULL) {
fclose(in);
return 1;
}Read mode leaves the observations unchanged and requires the input file to exist. Append mode preserves previous summaries and attempts to create the audit file if it is absent. Each pointer must be checked against NULL before it is used. If the second opening fails, the already-open input stream still needs closing.
The required modes are "r" for the observations and "a" for the audit file.
b) The program uses the following loop. Find the final values of chunks and chars, showing what each successful read stores.
char buf[5];
int chunks = 0;
int chars = 0;
while (fgets(buf, sizeof buf, in) != NULL) {
chunks++;
chars += (int)strlen(buf);
}First reserve one array position for the terminating null character. The maximum input capacity is ________ per call because 5−1=4.
The first call stores owl\n, containing ________, and then adds '\0'. The second call stores badg, also containing ________, and adds its terminator. The third call stores er\n, containing three input characters, and adds its terminator.
strlen counts the characters before the terminating null, so it includes each stored newline but excludes the terminator. Therefore,
Three calls return non-null pointers, so chunks is incremented three times. The next call returns NULL at end-of-file and does not execute the loop body. In general, the program would check ferror(in) after the loop before treating these totals as a complete audit.
The final values are chunks = 3 and chars = 11. The file contains two lines, illustrating why successful calls should not automatically be counted as complete lines.
c) The program next calls fprintf(log, "chunks=%d chars=%d\n", chunks, chars). What text does it append, what integer does the call return, and how should the streams be finished?
Substitute the two counters into the format string. The appended text is chunks=3 chars=11\n, where \n denotes one newline.
The prefix chunks= contributes ________, the digit 3 contributes one, and the separating space contributes one. The prefix chars= contributes ________, the digits 11 contribute two, and the newline contributes one. Thus,
There is no additional string terminator written to the file. Under the stated success assumption, fprintf returns 18.
Finally, call fclose(in) and fclose(log) once each and check both return values. A zero return indicates successful closing. In particular, checking the output close matters because pending buffered output may be written at that point; a positive fprintf return alone would not establish successful completion.
A C logging tool can use different output buffering policies, which govern when characters waiting in memory are passed to the destination. Match each policy to its defining behavior. Explicit flushing and closing are still available under every policy.
Groups characters for transfer when its memory area fills; a newline alone does not require transfer.
Passes output onward as soon as possible rather than retaining characters for later grouped delivery.
Transfers pending characters on a newline; filling its memory area can also trigger transfer.
Line-buffered output
Unbuffered output
Fully buffered output
An existing Unix text file contains exactly 47 single-byte letters followed by one newline, with no other characters. A program opens it successfully for reading and repeatedly calls fgets(buf, sizeof buf, in) using char buf[12] until the call returns NULL. Assume no read errors occur. How many calls return a non-null pointer? Answer in successful calls, as an exact integer.