Opening a File

To access a file (for reading or writing) in C, the first step is to open it. Opening a file creates a stream associated with that file. A stream is represented by a FILE * in C and refers to a sequence of data (like characters) that can be read or written. The stream has a current position that typically advances when a read or write operation is performed.

The fopen function is commonly used to open a file:

FILE * fopen(const char *filename, const char *mode);

Key Details about fopen:

The mode in which you open a file determines whether the file can be read, written, or both, and where the cursor starts in the file (beginning or end). Below is a summary of the modes:

Mode Read/Write File Exists? Truncate? Starting Position
r Read only Fails No Beginning
r+ Read/Write Fails No Beginning
w Write only Created Yes Beginning
w+ Read/Write Created Yes Beginning
a Write only Created No End
a+ Read/Write Created No End

Explanation of Modes:

For the a modes, all writes go to the end of the file, regardless of the current position.