简体   繁体   English

fprintf() 是否适用于在管道中写入,或者我必须始终使用 write()?

[英]Does fprintf() work for writing in a pipe, or I must always use write()?

Keep in mind that when using fprintf() I'm aware that I need to pass the file descriptor for writing to the pipe.请记住,在使用fprintf()我知道我需要传递文件描述符以写入管道。 I just have the doubt and wish to know right now;我现在只是有疑问并想知道; I don't really have any kind of sample code.我真的没有任何类型的示例代码。

In addition, I want to know if functions such as fputc(), fputs() will also work.另外,我想知道fputc()、fputs()等函数是否也能用。

Using fprintf() requires a file stream ( FILE * ).使用fprintf()需要一个文件流 ( FILE * )。 When you create a pipe, you get two file descriptors.创建管道时,您会获得两个文件描述符。 File descriptors are not the same as streams.文件描述符与流不同。

You can use the POSIX fdopen() function to create a file stream from a file descriptor;您可以使用 POSIX fdopen()函数从文件描述符创建文件流; you can then use fprintf() on that file stream — or any of the other standard I/O functions that take an explicit file stream argument and write to the stream.然后,您可以在该文件流上使用fprintf() — 或任何其他采用显式文件流参数并写入流的标准 I/O 函数。 You can't use fseek() ;你不能使用fseek() you'll get an error ( ESPIPE — illegal seek).你会得到一个错误( ESPIPE - 非法搜索)。

You can (in theory) use the POSIX dprintf() function to write directly to a file descriptor — if your system supports it.您可以(理论上)使用 POSIX dprintf()函数直接写入文件描述符——如果您的系统支持它。

You can use fdopen() to convert a file descriptor to a FILE * , and then use all the stdio functions.您可以使用fdopen()将文件描述符转换为FILE * ,然后使用所有 stdio 函数。

int pipefd[2];
pipe(pipefd);

FILE *pipeout = fdopen(pipefd[1], "w");
fprintf(pipeout, "Message written to the pipe\n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM