问题
When should we use fdopen and how do we use it? My understanding of that is when we can't use fopen to read (read from pipe). I don't really understand the description of fdopen on the man page: The fdopen() function associates a stream with the existing file descriptor, fd
.
回答1:
You use fdopen() when you have a file descriptor (int fd;
) of some sort but you need to call functions that require a file stream (FILE *fp;
) instead. This could be a pipe file descriptor, or a socket file descriptor, or any other file descriptor type.
Once you've used fdopen()
, you should not use the file descriptor again — you should use only the file stream. If you must use a file descriptor as well, it would be best to use fileno(fp)
rather than the saved fd
. Most importantly, if you mix access, you need to ensure that you've flushed the file stream before you do anything with the file descriptor. (There's no buffering with the file descriptor, so there's less of a problem reverting to the file stream from the file descriptor.). Operations that change the current file position on the file descriptor could mess up the file stream and vice versa (when there is a current position associated with the file descriptor or file stream). Note that both read and write operations change the current file position — there's not a lot you can do without risking a mess.
You must use fclose(fp);
to close the file stream (and implicitly the file descriptor). Do NOT use just close(fd)
or close(fileno(fp))
.
Note that POSIX defines dprintf() to do formatted output to a file descriptor. Also, you could use snprintf()
or its relatives to format data into a string and then write the string to the file descriptor. This might make it less important to use fdopen()
.
来源:https://stackoverflow.com/questions/61708092/posix-fdopen-function-in-c