FILE and fopen
- C course
- Intermediate
- Lesson 47/116
- 5 min
Learn the FILE struct and opening files with fopen.
FILE and fopen
To work with a file in C, you use a handle of type FILE*. The fopen function opens a file in a specific mode and returns this handle.
Example: FILE *f = fopen("test.txt", "w");. Here "w" is write mode (truncates existing content). Modes: "r" read, "w" write, "a" append. If fopen fails it returns NULL; that's why checking before use is required. File operations are declared in stdio.h; so #include <stdio.h> is needed.
NULL check
fopen isn't always successful. If the file doesn't exist, permission is denied, or the disk is full, it returns NULL. Operating on a NULL handle is undefined behavior; that's why checking is required.
Example pattern: FILE *f = fopen("x.txt", "r"); if (f == NULL) return 1;. This pattern safely exits the program when the file can't be opened. Production code does more detailed error handling; but the basic pattern is this. Putting a NULL check for every fopen is a sign of robust C code.
Practice Write to a file and confirm
Open a file in write mode with FILE *f = fopen("test.txt", "w");. Check with if (f == NULL) return 1;. Write with fprintf(f, "Merhaba\n");. Close with fclose(f);. Print confirmation with printf("Dosya yazıldı\n");.
Starter code
#include <stdio.h>
// Open a file with fopen (write mode)
// Write a line with fprintf
// Close the file with fclose
// Print 'Dosya yazıldı' with printf
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
FILE *f = fopen("test.txt", "w");
if (f == NULL) return 1;
fprintf(f, "Merhaba\n");
fclose(f);
printf("Dosya yazıldı\n");
return 0;
}Expected output
Dosya yazıldı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which mode opens a file for reading?
- r Correct answer
- a
- rw
- w
Explanation: The "r" mode opens a file for reading.
2 Complete the fopen call
FILE *f = fopen("notlar.txt", "____");
FILE *f = fopen("notlar.txt", "w");
Explanation: The "w" mode opens the file for writing.
3 Match modes to purpose
| Term | Meaning |
|---|---|
"r" |
Read mode |
"w" |
Write mode |
"a" |
Append mode |
NULL |
Open failed |