Search code examples
cposix

Properly close a file with both a file descriptor and file pointer


For formatted writes with fprintf(), I'm using a FILE pointer obtained from a file descriptor created by mkstemp() (see this link):

fd = mkstemp(tmpName);

FILE *fp = fdopen(fd, "w");
fprintf(fp, "#EXTM3U\n");

What is the proper procedure to close the file?

fclose(fp) // only?

fclose(fp); // both?
close(fd);

close(fd); // only?

Solution

  • From the docs:

    The fdopen() function associates a stream with the existing file descriptor, fd.

    [...]

    The file descriptor is not dup'ed, and will be closed when the stream created by fdopen() is closed.

    Please also note:

    The mode of the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be compatible with the mode of the file descriptor.