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