Concept Flow - File modes
Start
Open file with mode
Check if file opened
Read/Write/Append
Close file
End
Open a file with a mode, check success, perform actions, then close the file.
#include <stdio.h> int main() { FILE *f = fopen("test.txt", "w"); if (f == NULL) { perror("Failed to open file"); return 1; } fprintf(f, "Hello\n"); fclose(f); return 0; }
| Step | Action | File Pointer (f) | Result/Output |
|---|---|---|---|
| 1 | Call fopen("test.txt", "w") | Non-NULL (file opened) | File opened for writing |
| 2 | Call fprintf(f, "Hello\n") | Non-NULL | Writes 'Hello' to file |
| 3 | Call fclose(f) | Non-NULL before close | File closed |
| 4 | Return 0 | Pointer value unchanged | Program ends |
| Variable | Start | After fopen | After fprintf | After fclose | Final |
|---|---|---|---|---|---|
| f | undefined | pointer to file | pointer to file | pointer to file (closed) | pointer to file (closed) |
File modes in C control how files are opened: "r" = read only "w" = write (create or overwrite) "a" = append (write at end) Always check fopen returns NULL before use. Use fclose to close files and save data.