在c中重定向标准输出然后重置标准输出
我正在尝试使用 C 中的重定向将输入重定向到一个文件,然后将标准输出设置回打印到屏幕上。有人能告诉我这段代码有什么问题吗?
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv) {
//create file "test" if it doesn't exist and open for writing setting permissions to 777
int file = open("test", O_CREAT | O_WRONLY, 0777);
//create another file handle for output
int current_out = dup(1);
printf("this will be printed to the screen\n");
if(dup2(file, 1) < 0) {
fprintf(stderr, "couldn't redirect output\n");
return 1;
}
printf("this will be printed to the file\n");
if(dup2(current_out, file) < 0) {
fprintf(stderr, "couldn't reset output\n");
return 1;
}
printf("and this will be printed to the screen again\n");
return 0;
}
I'm trying to use redirects in C to redirect input to one file and then set standard output back to print to the screen. Could someone tell me what's wrong with this code?
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv) {
//create file "test" if it doesn't exist and open for writing setting permissions to 777
int file = open("test", O_CREAT | O_WRONLY, 0777);
//create another file handle for output
int current_out = dup(1);
printf("this will be printed to the screen\n");
if(dup2(file, 1) < 0) {
fprintf(stderr, "couldn't redirect output\n");
return 1;
}
printf("this will be printed to the file\n");
if(dup2(current_out, file) < 0) {
fprintf(stderr, "couldn't reset output\n");
return 1;
}
printf("and this will be printed to the screen again\n");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在此之前,您必须确保做的一件事是在从其下面切换
stdout
文件描述符之前调用fflush(stdout);
。可能发生的情况是,C 标准库正在缓冲您的输出,但没有意识到您正在移动它下面的文件描述符。您使用printf()
写入的数据实际上不会发送到底层文件描述符,直到其缓冲区变满(或者您的程序从main
返回) >)。像这样插入调用:
在对
dup2()
的两次调用之前。One thing you'll have to make sure to do before that will work at all, is to call
fflush(stdout);
before switching thestdout
file descriptor out from under it. What's probably happening is that the C standard library is buffering your output, unaware that you're shifting around the file descriptors underneath it. The data you write usingprintf()
isn't actually sent to the underlying file descriptor until its buffer becomes full (or your program returns frommain
).Insert the call like this:
before both calls to
dup2()
.您的第二个 dup2 调用是错误的,替换为:
Your second
dup2
call is wrong, replace with:只需将 dup2(current_out, file) 替换为 dup2(current_out, 1) 即可,效果应该会更好。
Just replace
dup2(current_out, file)
withdup2(current_out, 1)
, and things should work better.