gpt4 book ai didi

c - 如何将文件内容写入管道?

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:03 25 4
gpt4 key购买 nike

我有这个代码:

            close(pipefd[0]);

fp = fopen(argv[1], "r");

if(fp)
{
while((c = getc(fp)) != EOF)
{
if((write(pipefd[1], c, 1)) < 1)
{
fprintf(stderr, "Write to pipe failed.\n");
exit(EXIT_FAILURE);
}
}
}

fclose(fp);

close(pipefd[1]);
waitpid(childPID, &status, 0);
exit(EXIT_SUCCESS);

根据我的理解,它应该打开一个文件并将其内容写入管道。这然后成为另一个程序的标准输入。我的测试表明除写入外一切正常,但我不知道为什么它不起作用。

我是不是在做傻事?

编辑:是的,我在做一些愚蠢的事情。

我认为问题出在我的写入上(在我修复 c 需要是 &c 之后),但它实际上是在我的子进程中,我在其中使用 dup2() 将管道的读取端链接到标准输入我的 child 过程。我的论点倒退了。这是工作代码,从 fork() 开始:

childPID = fork();
if (childPID == 0)
{
//child code
//printf("In the child process.\n");
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[1]);

execv(argv[2], paramList);
printf("You shouldn't be seeing this.\n");
}
else
{
//parent code
//printf("In the parent process\n");
close(pipefd[0]);

fp = fopen(argv[1], "r");

if(fp)
{
while((c = getc(fp)) != EOF)
{
if((write(pipefd[1], &c, 1)) < 1)
{
fprintf(stderr, "Write to pipe failed.\n");
perror("write");
exit(EXIT_FAILURE);
}
}
}

fclose(fp);

close(pipefd[1]);
waitpid(childPID, &status, 0);
exit(EXIT_SUCCESS);
}

希望这能帮助其他人不必连续四天用头撞 table !并感谢所有花时间回答问题的人。

最佳答案

write() 接受一个指向要写入的数据缓冲区的指针,而不是一个字符(本质上是一个数字)。

答案很简单,不是将c传递给write(),而是传递c的地址,即。 &c

关于c - 如何将文件内容写入管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com