如何将标准输入重定向到文件?

问题描述

我想将stdin重定向到文件,以便可以写入文件,然后程序打印字符。 下面是一个简单的C代码片段,其中显示了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 < testfile.txt

调用程序

然后我echo efghi > testfile.txt,但是什么也没有发生。 如果我用abcd预填充文件,则在程序启动后会立即打印abcd,但是我再也无法将某些东西回显到测试文件中。

是否可以通过这种方式重定向标准输入?

解决方法

我认为您可以使用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;
}

但是,您需要使用>>附加到文件,例如:

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
,

您还可以使用与重定向相关联的heredoc <<到这样的文件中:

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...