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);
filename
: A string (null-terminated) representing the path of the file to be opened. The path can be either absolute (starting with /
) or relative to the program’s current working directory.mode
: A string specifying the mode in which the file should be opened (e.g., read, write, append).Key Details about fopen
:
fopen
, it results in a FILE *
that you can use to read from or write to the file.fopen
call fails (e.g., the file doesn’t exist or you lack the necessary permissions), it returns NULL
and sets the global variable errno
accordingly.fopen
returned NULL
before proceeding with any file operations.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:
r
: Opens a file for reading. If the file does not exist, the function fails.r+
: Opens a file for both reading and writing. If the file does not exist, the function fails.w
: Opens a file for writing. If the file exists, its contents are truncated. If it doesn’t exist, it is created.w+
: Opens a file for reading and writing. If the file exists, its contents are truncated. If it doesn’t exist, it is created.a
: Opens a file for appending (writing to the end). If the file does not exist, it is created.a+
: Opens a file for reading and writing, with all writes appended to the end. If the file does not exist, it is created.For the a
modes, all writes go to the end of the file, regardless of the current position.