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
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("notes.txt", "w");
5 
6 if (fp == NULL) {
7 printf("Could not open the file\n");
8 return 1;
9 }
10 
11 fprintf(fp, "Hello from C\n");
12 fclose(fp);
13 
14 printf("File opened and data saved\n");
15 return 0;
16}
Output
File opened and data saved

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
CCode Cell
1FILE *fp = fopen("input.txt", "r");
2 
3if (fp == NULL) {
4 printf("Could not open input.txt\n");
5 return 1;
6}
7 
8/* Work with the file here. */
9fclose(fp);
Output
If input.txt cannot be opened, the error message is displayed.
📝 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