YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Working with inputChapter 53 of 73

Opening files, modes, and lifetimes

Choose read, write, append, update, and exclusive-creation modes while managing stream ownership and close failures.

6 min readIntermediateC17 baseline
Offline reading
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

ModeEffect
rOpen an existing text file for reading; fail if it cannot be opened.
wCreate a text file or truncate an existing one to zero length.
aCreate 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, wbxC11 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.

Complete C17 program
#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

Complete C17 program
#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

Complete C17 program
#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

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.
Explain it in your own words

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.

What should you check after fopen before using the stream?
Read the explanation for every choice
  1. Whether the returned pointer is NULL.

    ✓ Correct reasoning. NULL indicates failure to open; using it as a valid stream would violate the interface contract.

  2. Whether the returned pointer equals EOF.

    EOF is an integer macro used by other I/O interfaces, not fopen’s failure pointer.

  3. 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/fscanf handle formatted text, just like their console counterparts.
  • fgets/fputs handle line-oriented text.
  • fread/fwrite transfer 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.

CHAPTER 53 / 73

In this chapter

Opening files, modes, and lifetimes

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping