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.
-
Standard Streams: Automatically opened when the program starts:
stdin(Standard Input: Keyboard)stdout(Standard Output: Console)stderr(Standard Error: Console for error messages)
-
File Stream: To work with a file, we use the
FILEstructure, 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):
| Mode | Description | Action if file exists | Action if file doesn't exist |
|---|---|---|---|
r | Read mode | Opens for reading | Returns NULL (Error) |
w | Write mode | Destroys content (truncates) | Creates new file |
a | Append mode | Writes to end of file | Creates new file |
r+ | Read/Update | Opens for reading and writing | Returns NULL |
w+ | Write/Update | Destroys content, opens R/W | Creates new file, opens R/W |
a+ | Append/Update | Opens R/W, write operations append | Creates new file, opens R/W |