Concept Flow - Opening and closing files
Start
Call fopen()
Check if file opened?
No→Handle error
Yes
Use file pointer
Call fclose()
End
Open a file with fopen(), check success, use the file, then close it with fclose().
#include <stdio.h> int main() { FILE *fp = fopen("test.txt", "r"); if (fp == NULL) return 1; fclose(fp); return 0; }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call fopen("test.txt", "r") | File exists? | Returns FILE pointer or NULL |
| 2 | Check if fp == NULL | fp is not NULL | File opened successfully |
| 3 | Use file pointer (not shown here) | N/A | File ready for operations |
| 4 | Call fclose(fp) | Close file | File closed |
| 5 | Return 0 | Program ends | Success exit |
| Variable | Start | After fopen | After fclose | Final |
|---|---|---|---|---|
| fp | undefined | FILE pointer (not NULL) | Still FILE pointer | No longer used after fclose |
Opening a file: FILE *fp = fopen("filename", "mode");
Check if fp == NULL to ensure success.
Use fp for file operations.
Close file with fclose(fp) to free resources.
Always check fopen result before using the file.