简体   繁体   English

用fwrite()将stdin写入文件

[英]writing stdin into a file with fwrite()

I have to capture the stdout in a program and write that into a file...so I created a pipe. 我必须在程序中捕获标准输出并将其写入文件...所以我创建了管道。 In the parent process, I captured the stdout in the pipe using dup() and I need to get this into a file...so I did a dup() in the child to get the captured file descriptor into the stdin. 在父进程中,我使用dup()捕获了管道中的stdout,我需要将其保存到文件中...所以我在子进程中进行了dup()来将捕获的文件描述符保存到stdin中。 Now, how do I write this stdin into a file using fwrite()? 现在,如何使用fwrite()将此stdin写入文件?

Isn't that doing things the hard way? 这不是很难做的事情吗? All you need to do in the parent is use freopen() to connect stdout to the file of your choosing. 在父级中您需要做的就是使用freopen()将stdout连接到您选择的文件。

FILE *fp = freopen("/tmp/mylogfile", "w", stdout);

if (fp == 0)
    error("...something went wrong opening the log file...\n");

The direct answer to your question is: 您问题的直接答案是:

char buffer[32768];
ssize_t nbytes;
FILE *fp = fopen("/tmp/mylogfile", "w");

if (fp == 0)
    error("....something went wrong opening my log file...\n");

while ((nbytes = fread(buffer, sizeof(char), sizeof(buffer), stdin)) > 0)
    if (fwrite(buffer, sizeof(char), nbytes, fp) != nbytes)
        error("...something went wrong writing to standard output...\n");

However, this is hardly necessary. 但是,这几乎没有必要。 You can improve the error handling in all sorts of ways; 您可以通过各种方式改进错误处理; I'm simply assuming that 'error()' reports a message and does not return. 我只是假设“错误()”报告中的消息,并没有返回。

The easiest way is just to open the file and provide that as the child's stdout: 最简单的方法是打开文件并将其提供为孩子的标准输出:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

#include <stdio.h>

int main() {
  pid_t pid = fork();
  switch (pid) {
  case -1:
    perror("fork");
    return 1;

  case 0:;
    int new_out = open("output.txt", O_WRONLY | O_CREAT, 0666);
    if (new_out == -1) {
      perror("open");
      return 1;
    }
    if (dup2(new_out, 1) == -1) {
      perror("dup2");
      return 1;
    }
    char* args[] = {"/bin/echo", "test output", 0};
    execv(args[0], args);
    perror("exec");
    return 1;

  default:;
    int s;
    if (waitpid(pid, &s, 0) == -1) {
      perror("waitpid");
      return 1;
    }
    if (WIFEXITED(s)) {
      return WEXITSTATUS(s);
    }
    return 1;
  }
}

You should capture into a byte or char buffer and the send that ot the fwrite. 您应该捕获到字节或char缓冲区中,然后将其发送给fwrite。 When I say a buffer I mean an array or dynamically allocated block of bytes/chars. 当我说一个缓冲区时,我的意思是一个数组或动态分配的字节/字符块。

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

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