开发者

`echo "asdf"` to a C program using pipes

开发者 https://www.devze.com 2023-03-22 18:47 出处:网络
Basically, I\'m trying to implement the following: echo \"asdf\" | ./a.out where ./a.out simply prints out \"asdf\"

Basically, I'm trying to implement the following:

echo "asdf" | ./a.out

where ./a.out simply prints out "asdf"

I know this is probably noob C stuff, but as I'm only a novice C programmer, I thought I'd ask the community.


Update:

OK, I got it:

#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", s开发者_开发百科tr);

  return 0;
}

echo "asdf" | ./a.out does what I need.


It is coming through 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
$


Just read from the standard input file stdin to read the piped in contents.

0

精彩评论

暂无评论...
验证码 换一张
取 消