cs24-23fa fclose

Introduction to Computing Systems (Fall 2023)

Name

fclose - close a stream

Synopsis

#include <stdio.h>

int fclose(FILE *stream);

Description

The fclose() function flushes the stream pointed to by stream (writing any buffered output data using fflush()) and closes the underlying file descriptor.

Example

#include <assert.h>
#include <stdio.h>

int main() {
    FILE *file = fopen("log.txt", "w");
    assert(file != NULL); // the file should be opened successfully

    // Write some text to the file
    fprintf(file, "1 + 2 is %d\n", 1 + 2);

    int close_result = fclose(file);
    assert(close_result == 0); // the file should be closed successfully
}

See also the fopen() example.

Return Value

Upon successful completion, 0 is returned. Otherwise, EOF is returned and errno is set to indicate the error. In either case, any further access (including another call to fclose()) to the stream results in undefined behavior.

Errors

EBADF
The file descriptor underlying stream is not valid.

fclose() may also fail and set errno for any of the errors specified for close(), write(), or fflush().

See Also

fopen(), fread(), fwrite(), fflush(), fseek()