我遇到了一些库函数的问题。 我需要编写一些使用库函数的C代码,该函数会在屏幕上打印它的内部步骤。 我不关心它的返回值,只关心它所打印的步骤。 因此,我认为我应该从标准输出中读取,并将读取的字符串复制到缓冲区。 我已经尝试使用fscanf和dup2,但无法从标准输出中读取。请问有人可以帮帮我吗?
以下是不使用文件并将stdout捕获到管道中的先前答案的扩展版本:
#include <stdio.h>
#include <unistd.h>
main()
{
int stdout_bk; //is fd for stdout backup
printf("this is before redirection\n");
stdout_bk = dup(fileno(stdout));
int pipefd[2];
pipe2(pipefd, 0); // O_NONBLOCK);
// What used to be stdout will now go to the pipe.
dup2(pipefd[1], fileno(stdout));
printf("this is printed much later!\n");
fflush(stdout);//flushall();
write(pipefd[1], "good-bye", 9); // null-terminated string!
close(pipefd[1]);
dup2(stdout_bk, fileno(stdout));//restore
printf("this is now\n");
char buf[101];
read(pipefd[0], buf, 100);
printf("got this from the pipe >>>%s<<<\n", buf);
}
生成以下输出:
this is before redirection
this is now
got this from the pipe >>>this is printed much later!
good-bye<<<
您应该能够打开一个管道,将写端复制到stdout中,然后从管道的读端读取数据。以下是示例代码(包括错误检查):
int fds[2];
pipe(fds);
dup2(fds[1], stdout);
read(fds[0], buf, buf_sz);
FILE *fp;
int stdout_bk;//is fd for stdout backup
stdout_bk = dup(fileno(stdout));
fp=fopen("temp.txt","w");//file out, after read from file
dup2(fileno(fp), fileno(stdout));
/* ... */
fflush(stdout);//flushall();
fclose(fp);
dup2(stdout_bk, fileno(stdout));//restore
我假设你指的是标准输入。另一个可能的函数是gets
,使用man gets
来了解它的工作原理(非常简单)。请展示你的代码并解释你失败的地方,以便得到更好的答案。
stdout
的库函数,并且他想要拦截该输出。 - Carl Norum
dup2
,那么您应该已经能够完成您正在尝试的操作。 - Carl Norum