CodeBlanks Logo Icon CodeBlanks

fclose

  • C course
  • Intermediate
  • Lesson 50/116
  • 5 min

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.

Practice 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);.

Starter code

main.c
#include <stdio.h>

// Open log.txt with fopen (write mode)
// Write a line with fprintf, close with fclose
// Reopen in read mode, read with fgets, close
// Print the read content with printf

int main(void) {
    return 0;
}

Sample solution

main.c
#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;
}

Expected output

Okundu: Tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why should we close files?

  • Runs faster
  • Compiler requires it
  • Memory grows
  • Flushes buffer and releases resources Correct answer

Explanation: fclose flushes the buffer and releases file resources.

2 Match fclose concepts

Term Meaning
fclose(f) Close file
fflush(f) Flush buffer
buffer Buffer
resource leak Resource leak

3 Complete the fclose call

Question
FILE *f = fopen("x.txt", "w");
____(f);
Answer
FILE *f = fopen("x.txt", "w");
fclose(f);

Explanation: fclose(f) closes the file and flushes the buffer.

All lessons in Intermediate