Thuta Learning
C
AdvancedProgrammingbeginner

File I/O

What you'll walk away with

  • Explain the C language and runtime behavior of File I/O
  • Test normal, boundary, invalid, and failure cases
  • Use warnings and sanitizers to write safer C

Always check open, read, write, and close operations; a file operation can fail after opening successfully.

Build a Complete Mental Model

C file I/O requires explicit handling of open modes, errors, partial reads or writes, buffering, text versus binary behavior, and close results. Check every FILE operation and centralize cleanup.

Apply It in Real C

Implement a text-file write and read round trip with paths for permission failure, missing file, write error, and close error.

After This Lesson

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *file = fopen("notes.txt", "w");
    if (file == NULL) { perror("notes.txt"); return EXIT_FAILURE; }

    int status = EXIT_SUCCESS;
    if (fputs("Safe C file I/O\n", file) == EOF) {
        perror("write");
        status = EXIT_FAILURE;
    }
    if (fclose(file) == EOF) {
        perror("close");
        status = EXIT_FAILURE;
    }
    return status;
}
You should see
notes.txt contains: Safe C file I/O

Try It Yourself

Implement a text-file write and read round trip with paths for permission failure, missing file, write error, and close error.

Memory and Safety Warning

Using a FILE pointer without checking fopen can dereference null and invoke undefined behavior.

GNU C compiler diagnosticsGNU Project

Easy traps

  • Using a FILE pointer without checking fopen can dereference null and invoke undefined behavior.
  • Assuming one correct output proves bounds, lifetime, overflow, and ownership are all correct.

Hands-on Exercise

Implement a text-file write and read round trip with paths for permission failure, missing file, write error, and close error.

You'll know it worked when: A file is written or a clear error is returned.