`echo“asdf”`使用管道的C程序

时间:2011-07-22 13:12:31

标签: c pipe

基本上,我正在尝试实施以下内容:

echo "asdf" | ./a.out

其中./a.out只打印出“asdf”

我知道这可能是noob C的东西,但由于我只是一名新手C程序员,我以为我会问社区。


更新

好的,我明白了:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char str[80];
  int i;

  printf("Enter a string: ");
  fgets(str, 10, stdin);

  /* remove newline, if present */
  i = strlen(str)-1;
  if( str[ i ] == '\n') 
      str[i] = '\0';

  printf("This is your string: %s", str);

  return 0;
}

echo "asdf" | ./a.out做我需要的。

2 个答案:

答案 0 :(得分:2)

它正在通过stdin

$ cat stdin.c
#include <stdio.h>
int main () {
    int c;
    while (EOF != (c = fgetc (stdin)))
        putc (c, stdout);
}
$ gcc stdin.c
$ echo "foo" | ./a.out
foo
$

答案 1 :(得分:0)

只需阅读标准输入文件stdin即可阅读管道内容。