文件描述符的类似“fprintf”的函数(即 int fd 而不是 FILE* fp)
也许我只是想念它,但是是否有一个与文件描述符的 fprintf 等效的函数,甚至是在它们之间临时翻转的方法?
Maybe I'm just missing it, but isn't there a function equivalent to fprintf for file descriptors, or even a way to temporarily flip-flop between them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以查看
dprintf
(GNU 扩展,不在 C 或 POSIX 中):编辑 正如你们中的一些人在评论中指出的那样,POSIX 2008 标准化了这些函数。
You could look into
dprintf
(GNU extensions, not in C or POSIX) :EDIT As pointed by several of you in the comments, POSIX 2008 standardized these functions.
没有 C 或 POSIX(编辑:2008 年之前)标准函数可以对文件描述符执行
printf
操作,但您可以将文件描述符“打开”为FILE *
使用 POSIX 标准fdopen(int desc, const char *mode)
。我不确定直接翻转回使用描述符的支持有多好,但我猜如果您先刷新缓冲区,它可能会起作用......当然,您可以使用诸如
vsprintf
,但显然你必须处理缓冲。There is no C or POSIX (edit: prior to 2008) standard function to do
printf
on a file descriptor, but you can “open” a file descriptor as aFILE *
with the POSIX-standardfdopen(int desc, const char *mode)
. I'm not sure how well supported flipping back to using the descriptor directly is, but I'm guessing it might work if you flush the buffer first…Of course you could just implement your own using something like
vsprintf
, but obviously you then have to take care of the buffering.无论如何,由于
dprintf
不是 POSIX 函数,如果可移植性是一个问题,可以使用以下函数:最有可能想要检查
write
的返回值,但你已经了解了总体思路。显然,这不像 FILE * 例程那样进行缓冲;我更多地寻找格式说明符和构建将写入文件描述符的字符数据的能力,而不是担心在写入数据时缓冲数据。For what it's worth, since
dprintf
is not a POSIX function, one could use the following if portability is an issue:Most likely would want to check the return value of
write
, but you get the general idea. Obviously, this does not buffer like theFILE *
routines do; I was looking more for the format specifiers and the ability to build the character data that would be written to the file descriptor, rather than worrying about buffering the data as it is being written.不,没有标准,但两者做不同的事情。 fprinft 作为 stdio 的一部分,执行缓冲区读取和写入等操作,支持 ungetc 等。使用 fd 可以绕过所有这些并直接调用操作系统。
所以它们不可互换。如果不出意外的话,它们之间的翻转会搞砸 stdio 缓冲
No, there isn't as standard, but the two do different things. fprinft, as part of stdio, does things like buffer reads and writes, supports ungetc etc. Using a fd bypasses all that and calls the OS directly.
So they're not interchangeable. Flip flopping between them would screw up stdio buffering if nothing else
您可以将文件描述符作为普通文件打开,该文件可以由
fprintf()
使用 fdopen。You can open the file descriptor as a normal file that can be handled by
fprintf()
with fdopen.