C
fclose
Learn to close files with fclose.
fclose
fclose closes an open file. It flushes the buffer; that is, it writes unwritten data to disk. This prevents data loss.
Example: FILE *f = fopen("x.txt", "w"); fprintf(f, "veri"); fclose(f);. If fclose isn't called, the data written by fprintf may stay in the buffer and not reach the disk. Files close automatically at program end but this isn't reliable; especially in long-running programs. Pairing every fopen with an fclose is a core rule of robust C code.
Resource leak
Not closing files creates a resource leak. Each open file uses a file descriptor; their number is limited. In long-running programs, leaks lead to file open failures.
Example: a server that opens files per request without closing them eventually makes fopen return NULL. So calling fclose is not optional but mandatory. fflush(f) flushes the buffer but keeps the file open; this is useful when you want to write to a file periodically. Robust code uses both functions consciously.
Exercise Write, close, reopen and read
Open with FILE *f = fopen("log.txt", "w"); (check NULL). Write with fprintf(f, "Tamam\n");, close with fclose(f);. Reopen with f = fopen("log.txt", "r"); (check NULL). Declare char line[64];; read with fgets(line, sizeof(line), f);. fclose(f);. Print with printf("Okundu: %s", line);.
Show example solution
#include <stdio.h>
int main(void) {
FILE *f = fopen("log.txt", "w");
if (f == NULL) return 1;
fprintf(f, "Tamam\n");
fclose(f);
f = fopen("log.txt", "r");
if (f == NULL) return 1;
char line[64];
fgets(line, sizeof(line), f);
fclose(f);
printf("Okundu: %s", line);
return 0;
}
Test yourself
-
Why should we close files?
- Runs faster
- Compiler requires it
- Memory grows
- Flushes buffer and releases resources
Show answer
Flushes buffer and releases resources — fclose flushes the buffer and releases file resources.
-
Match fclose concepts
- fclose(f)
- Close file
- fflush(f)
- Flush buffer
- buffer
- Buffer
- resource leak
- Resource leak
-
Complete the fclose call
FILE *f = fopen("x.txt", "w");
____(f);
Show answer
FILE *f = fopen("x.txt", "w");
fclose(f);
Next lesson: fread and fwrite