[英]Use cat output in another program with pipe in C
I want to run: cat
somefile | 我要运行:
cat
somefile | program
> outputText in a UNIX system. UNIX系统中的
program
> outputText。
I have looked at many things such as pipe, using popen, dup2, etc; 我看过很多东西,例如管道,使用popen,dup2等。 I am lost.
我搞不清楚了。
Basic code should be: 基本代码应为:
cat
produces using program
and do some magic, an then output the data into outputText. program
读取cat
产生的任何输出并做一些魔术,然后将数据输出到outputText中。 Any advice please? 有什么建议吗?
PS The files are binary files. PS这些文件是二进制文件。
UPDATE: 更新:
I found this code that works with the prescribed command above... But it does things I don't want. 我发现此代码可与上面的指定命令一起使用...但是它可以做我不想要的事情。
sort
? sort
? I tried erasing things, but then I get errors and the program doesn't run. cat
as binary cat
以二进制形式读取数据 Any tips please? 有什么建议吗?
int main(void)
{
pid_t p;
int status;
int fds[2];
FILE *writeToChild;
char word[50];
if (pipe(fds) == -1)
{
perror("Error creating pipes");
exit(EXIT_FAILURE);
}
switch (p = fork())
{
case 0: //this is the child process
close(fds[1]); //close the write end of the pipe
dup2(fds[0], 0);
close(fds[0]);
execl("/usr/bin/sort", "sort", (char *) 0);
fprintf(stderr, "Failed to exec sort\n");
exit(EXIT_FAILURE);
case -1: //failure to fork case
perror("Could not create child");
exit(EXIT_FAILURE);
default: //this is the parent process
close(fds[0]); //close the read end of the pipe
writeToChild = fdopen(fds[1], "w");
break;
}
if (writeToChild != 0)
{
while (fscanf(stdin, "%49s", word) != EOF)
{
//the below isn't being printed. Why?
fprintf(writeToChild, "%s end of sentence\n", word);
}
fclose(writeToChild);
}
wait(&status);
return 0;
}
This is my suggestion, as you wanted read and write binary files: 这是我的建议,因为您想读写二进制文件:
#include <stdio.h>
int main (void) {
if (!freopen(NULL, "rb", stdin)) {
return 1;
}
if (!freopen(NULL, "wb", stdout)) {
return 1;
}
char buf[4];
while (!feof(stdin)) {
size_t numbytes = fread(buf, 1, 4, stdin);
// Do something with the bytes here...
fwrite(buf, 1, numbytes, stdout);
}
}
To be able to read the output (stdout) of cat
, you don't need to pipe anything I found thanks to you guys! 为了能够读取
cat
的输出(stdout),您不需要传递我发现的任何东西,谢谢大家! I got sidetracked with piping... 我被管道缠住了...
so if you run " cat
somefile | program
", where somefile contains binary data... you will just see whatever somefile contains, reprinted on a terminal. 因此,如果您运行“
cat
somefile | program
”,其中somefile包含二进制数据...,您将只看到somefile包含的内容,并在终端上重新打印。
Thank you! 谢谢! Now I can finish writing my
program
. 现在我可以完成编写
program
。
/*program.c*/
int main()
{
int i, num;
unsigned char block[2];
while ((num = fread(block, 1, 2, stdin)) == 2)
{
for(i = 0; i < 2; i++)
{
printf("%02x", block[i]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.