Tsallaka zuwa abun ciki
Justice Tech School

File Handling

fopen opens a file with a mode: "r" read, "w" write (replaces), "a" append. fprintf and fgets write and read text, and fclose closes the file. Always check that fopen did not return NULL.

Example
FILE *f = fopen("notes.txt", "w");
if (f == NULL) return 1;
fprintf(f, "first\nsecond\n");
fclose(f);
f = fopen("notes.txt", "r");
char line[50];
while (fgets(line, sizeof line, f)) {
  printf("read: %s", line);
}
fclose(f);
remove("notes.txt");

Result

read: first
read: second

Exercise

Open a file for reading.

fopen("a.txt", "")

Quiz Test

What does fopen return on failure?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.