Nearby lessons

68 of 72

C - Open a File

The fopen() function opens a file and returns a file pointer. Learn its syntax, how to select a mode, and how to check whether opening the file was successful.

1. Syntax of fopen()

The fopen() function takes two arguments: the filename and the mode.

FILE *fp = fopen("notes.txt", "w");

Example01
Loading editor…

2. What Is a FILE Pointer?

A FILE * variable is used to access an opened file through C's file-handling functions. It does not contain the complete file content itself.

For example, FILE *fp; declares a file pointer named fp.

3. Check Whether the File Opened

Always check whether the returned pointer is NULL before reading or writing. Opening can fail if the file or folder is missing, or if the program does not have permission.

Example03
Loading editor…
📝 Key Takeaways
  • Use fopen(filename, mode) to open a file.
  • The returned FILE pointer is used for file operations.
  • If fopen fails, it returns NULL.
  • Close a successfully opened file with fclose().

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.