Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fclose — C23 stream function

`fclose(stream)` from `<stdio.h>` flushes the specified stream, delivers unwritten data to the host environment, discards unread input, closes the associated file, and disassociates the `FILE` object. It returns zero on success or `EOF` on failure.

Version: C23

Syntax

int fclose(FILE *stream);

fclose(stream) from <stdio.h> flushes the specified stream, delivers unwritten data to the host environment, discards unread input, closes the associated file, and disassociates the FILE object. It returns zero on success or EOF on failure.

The example creates a tmpfile(), writes the five bytes hello, obtains the position with ftell, and then calls fclose. Output 5 1 confirms the logical size before closing and a zero close status; the temporary file is removed at that point.

Even when fclose reports failure, the stream is disassociated and must not be flushed, closed, or otherwise used again. Check the status because failure to write buffered output may surface only during close. stream must designate an open stream; after the call, the pointer is invalid as a stream handle.

Examples

#include <stdio.h>

int main(void) {
    FILE *stream = tmpfile();
    if (stream == NULL) return 1;
    if (fputs("hello", stream) == EOF) { fclose(stream); return 1; }
    long position = ftell(stream);
    if (position < 0) { fclose(stream); return 1; }
    int closed = fclose(stream);
    printf("%ld %d\n", position, closed == 0);
    return closed == 0 ? 0 : 1;
}

Result

5 1

The example creates a `tmpfile()`, writes the five bytes `hello`, obtains the position with `ftell`, and then calls `fclose`. Output `5 1` confirms the logical size before closing and a zero close status; the temporary file is removed at that point.

Sources