0

I want to send data through a pipe to a simple c program:

#include <stdio.h>
int main(int argc, char const *argv[])
{
char message[100000];
scanf("%s", message);
printf("%s", message);
return 0;
}

For instance, I want to print to the terminal all the data from /etc/passwd. To do so, I type:

cat /etc/passwd | ./my_c_program

But it is not working, it just prints "##".

Iguananaut
  • 21,810
  • 5
  • 50
  • 63

1 Answers1

1

One of the easiest way is to use getline(). The man page describes the function as below:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.

By the way, keep in mind this paragraph:

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.

Below a working sample.

#include <stdio.h>

int main(int argc, char* argv)
{
  char* l = NULL;
  size_t n;
  while (getline(&l,&n, stdin) != -1 )
    {
      printf("%s",l);
    }
  free(l); // don't forget to release the allocated memory
           // mmh, yes, here it's not useful since the program
           // ends.
}

This answer is inspired by this SO reply.

Community
  • 1
  • 1
Amessihel
  • 5,891
  • 3
  • 16
  • 40