fopen() Open a file as a stream
fopen() Open a file as a stream
fopen() opens a file in a specified mode and returns a FILE pointer, or NULL on failure. Use b for binary and + for updates; w truncates existing files.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
FILE *fopen(const char *filename, const char *mode);
⚙️ Parameters
| filename Required | A string containing the path of the file to open. |
|---|---|
| mode Required | An opening mode such as "r", "w", "a", or "r+"; adding b selects binary mode. |
Returns: Returns a pointer to the FILE object on success, or NULL on failure.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Temporary data
⚠️ Warning Close the stream with fclose(). Mode "w" truncates an existing file, so confirm that truncation is intended before opening it.
💡 Tip The example creates and removes c_fopen_demo.txt. Running it requires write permission in the current directory, and the shown output assumes the file operations succeed.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QWhat is the difference between fopen modes r, w, and a?
Ar opens an existing file for reading; w creates an empty file or truncates an existing one; a creates the file if needed and writes at its end.
QWhat commonly causes fopen to return NULL?
ACommon causes include a missing file, an invalid path, insufficient permissions, or a mode incompatible with the file state. Check the result and use a diagnostic such as perror().
QWhat do b and + mean in an fopen mode string?
Ab selects binary mode, avoiding environment-specific text-stream transformations such as newline conversion. + selects update mode, allowing reading and writing within the limits of the base mode. For example, rb+ reads and writes an existing binary file, while wb+ creates or truncates a file. Update streams must also follow positioning or flushing rules when switching between reading and writing.