Eamorr
Eamorr

Reputation: 10022

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

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", str);

  return 0;
}

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

Upvotes: 1

Views: 1235

Answers (2)

phoxis
phoxis

Reputation: 61950

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

Upvotes: 0

Sebastian Mach
Sebastian Mach

Reputation: 39109

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
$

Upvotes: 2

Related Questions