【问题标题】:How to redirect stdin to a file?如何将标准输入重定向到文件?
【发布时间】:2020-12-09 02:45:00
【问题描述】:

我想将标准输入重定向到一个文件,以便我可以写入该文件并且我的程序会打印该字符。 下面是一个简单的c代码sn-p,打印stdin。

该程序使用 gcc 编译并在 virtualbox 中的 debian 4.19.0 上运行

//printchar.c

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    
    int c;
    
    while( (c = getchar()) !='.') {
        putchar(c); 
    }

    return EXIT_SUCCESS;
}

我用./printchar 0 &lt; testfile.txt调用程序

然后我 echo efghi &gt; testfile.txt 但没有任何反应。 如果我用 abcd 预填充文件,abcd 会在程序启动后立即打印,但我又无法将某些内容回显到 testfile。

不可以这样重定向stdin吗?

【问题讨论】:

  • 听起来你想要一个命名管道man mkfifo
  • 你可以试试这个:tail -f -n +1 testfile.txt | ./printcharecho defg &gt; testfile.txt 在另一个终端上。

标签: c linux redirect gcc stdin


【解决方案1】:

你也可以使用 heredoc &lt;&lt; 关联重定向到这样的文件:

    << keyCodeToStopWriting >> myFile
    first line
    second line
    keyCodeToStopWriting  //Stop the writing

在此示例中,我使用&gt;&gt; 在文件末尾添加行,但您可以使用&gt; 覆盖它

【讨论】:

    【解决方案2】:

    我认为你可以使用getchar这样来做到这一点:

    int main(void) 
    {
        int c;
    
        while(1)
        {
          c = getchar();
          if (c == '.') break;
          if (c != EOF)
          {
            putchar(c);
          }
          else
          {
            usleep(100);
          }
        }
    
        return 0;
    }
    

    或像这样使用read

    #include <stdio.h>
    #include <unistd.h>
    
    int main()
    {
      char c;
      int n;
      while(1)
      {
        n = read(0, &c, 1);
        if(n > 0)
        {
          if (c == '.') break;
          putchar(c);
        }
        else
        {
            usleep(100);
        }
      }
    
      return 0;
    }
    

    但是,您需要使用&gt;&gt; 附加到文件中,例如:

    touch testfile.txt           // create empty file
    ./printchar < testfile.txt   // start program
    echo hello >> testfile.txt   // append to file
    echo world >> testfile.txt   // append to file
    echo . >> testfile.txt       // append to file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2017-08-08
      • 2011-06-11
      • 1970-01-01
      相关资源
      最近更新 更多