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.

Categorystdio.h I/O
KindLibrary function
Header<stdio.h>
C standardC89 / C90

📝 Syntax

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

⚙️ Parameters

filename RequiredA string containing the path of the file to open.
mode RequiredAn 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏