2

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?
alk
  • 69,737
  • 10
  • 105
  • 255
Danny
  • 2,482
  • 3
  • 34
  • 48

2 Answers2

2

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.

alk
  • 69,737
  • 10
  • 105
  • 255
0

The man page for fdopen specifies the following:

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

The man page for fclose supports this:

The fclose() function shall perform the equivalent of a close() on the file descriptor that is associated with the stream pointed to by stream

So, fclose is enough...

Daniel Trugman
  • 8,186
  • 20
  • 41
  • How does this relate to the information given in https://stackoverflow.com/a/13691168/1187415 and http://pubs.opengroup.org/onlinepubs/9699919799/functions/fclose.html ? *"The fclose() function shall perform the equivalent of a close() on the file descriptor that is associated with the stream pointed to by stream"* – Martin R Oct 03 '17 at 16:57
  • @MartinR, you are right! I stand corrected. – Daniel Trugman Oct 03 '17 at 17:53