File Handling & I/O

Master file operations in C: streams, buffering, text vs binary modes, and low-level POSIX I/O for real system programming.

The FILE* Stream

C uses a stream abstraction. A FILE pointer tracks the file, position, and error state.

file_ops.c
FILE *fp = fopen("data.txt", "r"); if (fp == NULL) { perror("Error opening file"); return 1; } // Read/Write operations here... fclose(fp);
Safety First: Always check if fopen returns NULL before using the file pointer. Always fclose to flush buffers and release resources.

File Modes

How you intend to use the file determines the mode string.

Read Mode ("r")

Opens existing file for reading. Fails if file doesn't exist. Pointer at start.

Write Mode ("w")

Creates new file for writing. DESTROYS content if file exists. Pointer at start.

Append Mode ("a")

Writes to the end of file. Preserves content. Creates file if missing.

Update Modes ("+")

"r+": Read/Write (File must exist)
"w+": Read/Write (Truncates file)
"a+": Read/Append

Text vs Binary

Understanding how data is serialized.

Text Mode

Translates newlines (\n -> \r\n on Windows). Good for human-readable logs.

fprintf(fp, "Score: %d\n", 100);

Binary Mode ("b")

Raw byte dump. No translation. Essential for images, structs, and custom formats.

fwrite(&data, sizeof(data), 1, fp);

Advanced I/O

Moving the cursor and checking status.

// Move to byte 100 from start fseek(fp, 100, SEEK_SET); // Get current position long pos = ftell(fp); // Check for End of File if (feof(fp)) { ... }

Low-Level POSIX I/O

System calls used by the OS kernel (Linux/Unix). Unbuffered and raw.

syscalls.c
#include <fcntl.h> #include <unistd.h> int fd = open("data.bin", O_RDONLY); char buf[1024]; ssize_t bytes = read(fd, buf, 1024); close(fd);