Concept Flow - Writing to files
Start
Open file with fopen
Check if file opened
Yes No
Write data
Close file with fclose
End
The program opens a file, checks if it opened successfully, writes data if yes, then closes the file.
#include <stdio.h> int main() { FILE *f = fopen("data.txt", "w"); if (f == NULL) return 1; fprintf(f, "Hello\n"); fclose(f); return 0; }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call fopen("data.txt", "w") | File exists or created | Returns file pointer (f) |
| 2 | Check if f == NULL | File opened? | Yes, file opened successfully |
| 3 | Call fprintf(f, "Hello\n") | Write string to file | String "Hello\n" written |
| 4 | Call fclose(f) | Close file | File closed |
| 5 | Return 0 | Program ends | Success |
| Variable | Start | After fopen | After fprintf | After fclose | Final |
|---|---|---|---|---|---|
| f | undefined | file pointer (valid) | file pointer (valid) | file pointer (valid) | file pointer (valid) |
Writing to files in C: - Use fopen(filename, mode) to open/create file - Check if fopen returns NULL (means error) - Use fprintf or fwrite to write data - Always fclose to save and close file - Return 0 on success
fopen in C?FILE *fp = fopen("output.txt", "w");
fprintf(fp, "Hello %s!", "World");
fclose(fp);FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp, "Test");1) FILE *fp = fopen("log.txt", "w");
fprintf(fp, "Line 1\n");
fprintf(fp, "Line 2\n");
fclose(fp);
2) FILE *fp = fopen("log.txt", "r");
fprintf(fp, "Line 1\n");
fclose(fp);
3) FILE *fp = fopen("log.txt", "w");
fprintf(fp, "Line 1\nLine 2\n");
// missing fclose
4) FILE *fp = fopen("log.txt", "a");
fprintf(fp, "Line 1\n");
fclose(fp);Pass the test and this pattern moves unknown