使用文件描述符和文件指针正确关闭文件

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

对于 fprintf() 的格式化写入,我使用了从 mkstemp() (see this link) 创建的文件描述符中获得的 FILE 指针:

fd = mkstemp(tmpName);

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

关闭文件的正确步骤是什么?

fclose(fp) // only?

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

close(fd); // only?

来自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.

另请注意:

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.

fdopen 的手册页指定了以下内容:

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

fclose 的手册页支持这一点:

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

所以,fclose 就够了...