C语言中的POSIX fdopen()函数 [英] POSIX fdopen() function in C

查看:104
本文介绍了C语言中的POSIX fdopen()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时应该使用fdopen以及如何使用它?我的理解是,当我们无法使用fopen进行读取(从管道读取)时.我不太理解手册页上的fdopen描述:The fdopen() function associates a stream with the existing file descriptor, fd.

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.

推荐答案

您使用 fdopen() ,当您具有某种文件描述符(int fd;),但需要调用需要文件流(FILE *fp;)的函数时.这可以是管​​道文件描述符,套接字文件描述符或任何其他文件描述符类型.

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.

使用完fdopen()后,应该不再使用文件描述符-您应该仅使用文件流.如果还必须使用文件描述符,则最好使用fileno(fp)而不是保存的fd.最重要的是,如果混合使用访问权限,则在使用文件描述符执行任何操作之前,需要确保已刷新文件流. (文件描述符没有缓冲,因此从文件描述符还原到文件流的问题较少.)更改文件描述符上当前文件位置的操作可能会使文件流混乱,反之亦然(当存在与文件描述符或文件流相关联的当前位置时).请注意,读取和写入操作都会更改当前文件的位置-在不引起混乱的情况下,您无能为力.

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.

您必须使用fclose(fp);关闭文件流(并隐式地关闭文件描述符).请勿仅使用close(fd)close(fileno(fp)).

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)).

请注意,POSIX定义 dprintf() 来执行格式化输出到文件描述符.另外,您可以使用snprintf()或其亲戚将数据格式化为字符串,然后将该字符串写入文件描述符.这可能会降低使用fdopen()的重要性.

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().

这篇关于C语言中的POSIX fdopen()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆