Opening files, modes, and lifetimes
Choose read, write, append, update, and exclusive-creation modes while managing stream ownership and close failures.
In this chapter8 sections
Opening a file chooses a policy: read existing data, create new data, replace contents, or append. That choice can change a file before any later write. We will connect modes, failures, and the responsibility to close an open stream.
1. Check acquisition before using the handle
fopen(name, mode) returns a FILE pointer on success and a null pointer on failure. Do not pass that null pointer to a read, write, or fclose call. File naming, directories, permissions, and which named files exist are host properties. Standard C does not define one universal path separator, current-folder policy, or permission model.
2. The mode states a data-preservation policy
| Mode | Effect |
|---|---|
r | Open an existing text file for reading; fail if it cannot be opened. |
w | Create a text file or truncate an existing one to zero length. |
a | Create if needed; writes are forced to the then-current end of the file. |
r+ | Read and write an existing text file without initial truncation. |
w+ | Read and write; create or truncate first. |
a+ | Read and append; create if needed. Writes still go to the end. |
wx, wbx | C11 exclusive creation: fail if the file already exists or cannot be created. |
Use a valid mode spelling such as rb or w+b for binary access or update. The x modifier is for eligible w/w+ creation forms, not a universal suffix for every mode. A failed fopen does not tell you which reason occurred just from its null return. When the distinction matters, use the documented diagnostics of the chosen platform.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *stream = fopen("codedile-note.txt", "wx");
if (stream == NULL) return EXIT_FAILURE;
int status = EXIT_SUCCESS;
if (fputs("Learning C.\n", stream) == EOF) status = EXIT_FAILURE;
if (fclose(stream) == EOF) status = EXIT_FAILURE;
return status;
}
This example creates a new note and refuses to overwrite an existing one. Run it in a suitable working folder; a second run fails while the note already exists. Changing wx to w would permit truncation. A prior “does this path exist?” check followed by w is not the same exclusive-creation operation and can introduce a race.
3. Append controls writes, not all reading behavior
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *stream = fopen("codedile-log.txt", "a");
if (stream == NULL) return EXIT_FAILURE;
int status = EXIT_SUCCESS;
if (fputs("next\n", stream) == EOF) status = EXIT_FAILURE;
if (fclose(stream) == EOF) status = EXIT_FAILURE;
return status;
}
Append mode directs each write to the current end even after intervening positioning operations. It does not promise that concurrent writers’ whole application records are atomic. With an update append stream, position explicitly before the intended reads and obey update-direction rules. Do not infer one portable initial read position merely from habits observed on one runtime.
4. One successful acquisition needs one ownership decision
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2) return EXIT_FAILURE;
FILE *stream = fopen(argv[1], "r");
if (stream == NULL) {
fputs("Could not open input.\n", stderr);
return EXIT_FAILURE;
}
int status = EXIT_SUCCESS;
int ch = fgetc(stream);
if (ch == EOF) {
if (ferror(stream)) status = EXIT_FAILURE;
else if (puts("empty") == EOF) status = EXIT_FAILURE;
} else if (printf("first=%c\n", ch) < 0) {
status = EXIT_FAILURE;
}
if (fclose(stream) == EOF) status = EXIT_FAILURE;
if (fflush(stdout) == EOF) status = EXIT_FAILURE;
return status;
}
This program owns the stream it opens and closes it on every path after acquisition. A helper receiving a borrowed FILE pointer should close it only if that transfer is part of the documented contract. Closing a stream disassociates it from its file even when fclose returns EOF. Do not retry fclose or inspect flags through that old handle; it is no longer a valid stream handle. Assigning one pointer variable to NULL can prevent accidental reuse there, but does not update aliases.
5. Text and binary describe stream translation
A text stream represents text under implementation rules; external representation can differ from the program’s characters, including line-ending translation. A binary stream supports transparent transfer of internal data under the standard’s binary-stream rules. Neither spelling validates a file format. Reading a serialized record still requires field widths, byte-order, representation, size, and error contracts.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 7.21.2–7.21.3, 7.21.5.1, 7.21.5.3, 7.21.7. Stable core provisions used for the C17 baseline; not the final ISO publication.
Before you move on
- An opening mode chooses reading, creation, replacement, append, or update behavior.
- The opening operation can fail or modify a file before a later write.
- Stream ownership includes the appropriate close operation and its possible failure.
Keep these ideas separate
- Text mode / External schema
- A stream mode controls translation and access behavior; it does not define a portable record format.
Which mode and failure policy would protect an existing file when the task requires creating a new destination?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Whether the returned pointer is NULL.
✓ Correct reasoning. NULL indicates failure to open; using it as a valid stream would violate the interface contract.
- Whether the returned pointer equals EOF.
EOF is an integer macro used by other I/O interfaces, not fopen’s failure pointer.
- Only whether the filename contains a dot.
The filename’s appearance does not prove that opening succeeded.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.
C treats files through an opaque FILE * handle obtained from fopen(filename, mode):
| Mode | Meaning |
|---|---|
"r" |
Read (file must already exist) |
"w" |
Write (creates the file, or truncates it if it exists) |
"a" |
Append (creates the file if it doesn't exist) |
"r+" |
Read and update |
"w+" |
Write and update (truncates) |
"a+" |
Append and update |
Appending "b" (e.g., "rb") opens the file in binary mode, disabling the newline translation that some platforms otherwise perform between \n and \r\n.
Reading and Writing
fprintf/fscanfhandle formatted text, just like their console counterparts.fgets/fputshandle line-oriented text.fread/fwritetransfer elements of the supplied byte size and return a count of complete elements. They also work on text streams; opening mode determines text translations.
Random Access
fseek, ftell, and rewind manage stream positions. For a text stream, a portable fseek uses offset 0, or a value returned by ftell for that file together with SEEK_SET; a text-stream ftell value is not necessarily a byte count. Binary streams use character offsets, but need not meaningfully support SEEK_END. Check fseek and ftell failures; fgetpos/fsetpos save and restore a file position plus the stream's multibyte conversion state, if any. Check fclose for EOF, especially after writing. Even on failure, the stream is disassociated; do not reuse it or retry fclose. Test feof/ferror after a read reports failure, not as a prediction before reading.
Update and binary streams: On a + update stream, switching from output to input requires fflush or a positioning operation. Switching from input to output requires a positioning operation unless the preceding input encountered end-of-file. Binary mode avoids text translations; it does not make raw structure dumps portable across padding, byte orders, or numeric representations.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.