Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 重复,但仍使用标准输出_C_File_Unix_Dup2 - Fatal编程技术网

C 重复,但仍使用标准输出

C 重复,但仍使用标准输出,c,file,unix,dup2,C,File,Unix,Dup2,我是否可以使用dup2(或fcntl)来实现一些魔法,从而将stdout重定向到一个文件(即,写入描述符1的任何内容都会转到一个文件),但如果使用其他机制,它会转到终端输出?如此宽松: int original_stdout; // some magic to save the original stdout int fd; open(fd, ...); dup2(fd, 1); write(1, ...); // goes to the file open on fd

我是否可以使用
dup2
(或
fcntl
)来实现一些魔法,从而将stdout重定向到一个文件(即,写入描述符1的任何内容都会转到一个文件),但如果使用其他机制,它会转到终端输出?如此宽松:

  int original_stdout;
  // some magic to save the original stdout
  int fd;
  open(fd, ...);
  dup2(fd, 1);
  write(1, ...);  // goes to the file open on fd
  write(original_stdout, ...); // still goes to the terminal

只需调用
dup
即可执行保存。以下是一个工作示例:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
  // error checking omitted for brevity
  int original_stdout = dup(1);                   // magic
  int fd = open("foo", O_WRONLY | O_CREAT);
  dup2(fd, 1);
  close(fd);                                      // not needed any more
  write(1, "hello foo\n", 10);                    // goes to the file open on fd
  write(original_stdout, "hello terminal\n", 15); // still goes to the terminal
  return 0;
}
#包括
#包括
#包括
int main()
{
//为简洁起见,省略了错误检查
int original_stdout=dup(1);//magic
int fd=开放(“foo”,O|u WRONLY | O|u CREAT);
dup2(fd,1);
关闭(fd);//不再需要
写入(1,“hello foo\n”,10);//转到fd上打开的文件
写(原文为“hello terminal\n”,15);//仍会转到终端
返回0;
}

可能希望使用
STDOUT\u FILENO
而不是神奇的数字。@EOF的想法是保留尽可能多的原始代码,它使用的是数字常量。此外,在Unix环境中,符号常量相当于拼写数字。文件描述符的数字引用通常由shell和脚本语言生成。使用宏
STDOUT\u FILENO
而不是
1
作为描述符编号将使代码更具可读性;我认为可读性非常重要。关于脚本语言,我不同意:例如
awk
sed
没有任何文件描述符的概念。gawk和mawk支持特殊名称
/dev/stdin
/dev/stdout
、和
/dev/stderr
(即使在Windows中)。那些了解文件描述符的脚本语言继承了C语言的概念(主要是接口),也有命名常量(例如Perl、Python)。@NominalAnimal可读性很重要,教育也很重要,特别是在so答案空间有限的情况下。提供的代码片段显示,只需添加
dup
,代码就可以保持不变地运行。随着时间的推移,OP将了解符号常量,也许正是从这些注释中。@user4815162342感谢您的回答。没想到这么简单。我以为
dup2
会关闭stdout。