How to assign input of echo in char array in C program? For example:
$ echo "Hello, world!" | ./hello
I need to save string "Hello, world" to an array.
How to assign input of echo in char array in C program? For example:
$ echo "Hello, world!" | ./hello
I need to save string "Hello, world" to an array.
The output of echo is piped to the input of hello. To get a string as an input in C, use fgets: http://www.cplusplus.com/reference/cstdio/fgets/. Here is some example code:
hello.c:
#include <stdio.h>
#include <string.h>
int main() {
char inputarr[256];
fgets(inputarr, 256, stdin);
//Credit to Tim Čas for the following code to remove the trailing newline
inputarr[strcspn(inputarr, "\n")] = 0;
printf("Value of inputarr: \"%s\"\n", inputarr);
}
Here is Tim's post about his code
Shell command:
$ gcc hello.c
$ echo "Hello, world!" | ./a.out
Value of inputarr: "Hello, world!"
$