Files and I/O Streams
suggest changeThe <stdio.h> header declares FILE and the standard stream functions. A FILE * refers to a stream; its representation is intentionally hidden.
Common operations include:
FILE *fopen(const char *restrict path, const char *restrict mode);
FILE *freopen(const char *restrict path, const char *restrict mode,
FILE *restrict stream);
int fclose(FILE *stream);
size_t fread(void *restrict buffer, size_t size, size_t count,
FILE *restrict stream);
size_t fwrite(const void *restrict buffer, size_t size, size_t count,
FILE *restrict stream);
int fseek(FILE *stream, long offset, int origin);
long ftell(FILE *stream);
void rewind(FILE *stream);
stdin, stdout, and stderr are predefined text streams available when a hosted program starts.
Opening Modes
| Mode | Behavior |
|---|---|
"r" |
Open an existing file for reading. |
"r+" |
Open an existing file for reading and writing. |
"w" |
Create or truncate a file for writing. |
"w+" |
Create or truncate a file for reading and writing. |
"a" |
Open or create a file for writing at the end. |
"a+" |
Open or create a file for reading and writing; writes occur at the end. |
Add b for binary mode, such as "rb" or "w+b". Text and binary streams can behave differently in newline translation, allowed byte sequences, and positioning. On implementations where they behave identically, b has no effect.
C11 added the x mode modifier for exclusive creation, such as "wx" or "wbx". The open fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (non-shared) access to the extent the underlying system supports it.
fopen returns a null pointer on failure. After a successful open, check each I/O operation and eventually call fclose; closing can itself fail because buffered output may be written at that point.
Positioning
fseek uses SEEK_SET, SEEK_CUR, or SEEK_END as the origin. For a binary stream, the new position is the offset in bytes from the origin, but a binary stream need not meaningfully support SEEK_END. For a text stream, the restrictions are tighter: use zero or a value previously returned by ftell as specified by the standard.
For large files, the range of long may be insufficient. Many platforms provide additional nonstandard interfaces with wider offsets.