将stdin重定向到文件

时间:2017-12-07 07:50:54

标签: c pipe

我想写一个程序,它接受我在终端输入的任何内容并将其写入文件。这是我写的代码。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int fd[2];
void pri(){
   char a[10];
   int ad=open("t.txt",O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
   if(read(fd[0],a,10)>0){
       write(ad,a,10);
   }   
}
int main()
{
   int a;
   char s[10];
   pipe(fd);
   while(read(0,s,10)>0){
      write(fd[1],s,10);
      pri();
   }
   return 0;
}

目前我正在使用数组和管道来实现这一目标。有没有什么方法可以在不使用任何数组的情况下实现相同的目标?

2 个答案:

答案 0 :(得分:1)

  

我想写一个程序,它接受我在终端输入的任何内容并将其写入文件。

这实际上非常简单,你不需要管道。 (您的应用程序本身扮演管道的角色。)

这就是我为证明这一点所做的:mycat.c

#include <stdio.h>

int main(int argc, char **argv)
{
  if (argc < 2) {
    fprintf(stderr, "ERROR: No output file!\n");
    fprintf(stderr, "Usage: mycat FILE\n");
    return 1;
  }
  FILE *fOut = fopen(argv[1], "w");
  if (!fOut) {
    fprintf(stderr, "ERROR: Cannot open file '%s' for writing!", argv[1]);
  }
  int c;
  while ((c = getc(stdin)) >= 0) {
    if (putc(c, fOut) < 0) {
      fprintf(stderr, "ERROR: Cannot write to file '%s'!", argv[1]);
    }
  }
  if (fclose(fOut)) {
    fprintf(stderr, "ERROR: Cannot write to file '%s'!", argv[1]);
  }
  return 0;
}

它从stdin读取一个字符并将其写入之前由fOut打开的文件流fopen()。重复此过程直到getc()失败,这可能发生,例如由于输入结束。

Cygwin / Windows 10上的bash示例会话:

$ gcc --version
gcc (GCC) 6.4.0

$ gcc -std=c11 -o mycat mycat.c

$ ./mycat
ERROR: No output file!
Usage: mycat FILE

$ ./mycat mycat.txt
Hello World.
tip tip tip

此时,我输入 Ctrl + D 来表示bash输入的结束。

$ cat mycat.txt
Hello World.
tip tip tip

$

我使用cat输出mycat.txt的内容。这是之前输入的内容(正如预期的那样)。

当我读到这个问题时,

cat实际上是我的第一个想法,但后来我想:这是一个标记为的问题(不是)。因此我的C示例代码。

为了完整性,与cat相同:

$ cat >mycat.txt <<'EOF'
> Hello cat.
> key key key
> EOF

$ cat mycat.txt
Hello cat.
key key key

$

我记得<<'EOF'是由bash解释的内容。因此,以下也适用:

$ ./mycat mycat.txt <<'EOF'
Hello World.
tip tip tip
EOF

$ cat mycat.txt 
Hello World.
tip tip tip

$ 

这让我相信cat的作用非常相似,虽然它将输入文件作为参数(s)并写入stdout(在调用它时可能会重新定向)如地狱)。与我的相反,如果没有提供参数,cat不会失败 - 它会从stdin读取。

答案 1 :(得分:0)

我想写一个程序,它接受我在终端输入的任何内容并将其写入文件。 =&gt;是的,可以相应地使用dup()dup2()close()系统调用。

char c;
int main(int argc,char *argv[])
{

        close(1);//so that it should not print anything on console 
        int ad=open(argv[1],O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
        // now ad is available file descriptor which is 1
        if(ad == -1){
                perror("open");
                return 0;
        }
        while(read(0,&c,1)>0){
                write(ad,&c,1);
        //when you don't want to take any input further press ctrl+d that will first save the data
        }
        return 0;
}

使用pipe进行输入重定向任务需要什么我的意思是你只想将用户输入重定向到文件中如果这只是一项任务,那么pipe()是不必要的,因为你没有进行任何形式的沟通b / w孩子或父母的过程。

相关问题