Back to course

File I/O Part 1: Streams and File Modes

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 47: File I/O Part 1: Streams and File Modes

File Input/Output (I/O) allows programs to read data from or write data to permanent storage (files). All C file handling functions are defined in <stdio.h>.

File Streams

C handles file operations using the concept of a stream. A stream is a sequence of bytes.

  1. Standard Streams: Automatically opened when the program starts:

    • stdin (Standard Input: Keyboard)
    • stdout (Standard Output: Console)
    • stderr (Standard Error: Console for error messages)
  2. File Stream: To work with a file, we use the FILE structure, which holds information about the file (location, buffer, position).

c FILE *file_ptr; // A pointer to a FILE structure

File Opening Modes

When opening a file, you must specify the purpose (mode):

ModeDescriptionAction if file existsAction if file doesn't exist
rRead modeOpens for readingReturns NULL (Error)
wWrite modeDestroys content (truncates)Creates new file
aAppend modeWrites to end of fileCreates new file
r+Read/UpdateOpens for reading and writingReturns NULL
w+Write/UpdateDestroys content, opens R/WCreates new file, opens R/W
a+Append/UpdateOpens R/W, write operations appendCreates new file, opens R/W