I want to redirect stdin to a file, so that I can write to the file and my program prints the character.
Below is a simple c code snippet, which prints stdin.
The programm is compiled with gcc and runs on debian 4.19.0 in virtualbox
//printchar.c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int c;
while( (c = getchar()) !='.') {
putchar(c);
}
return EXIT_SUCCESS;
}
I call the programm with ./printchar 0 < testfile.txt
Then i echo efghi > testfile.txt
but nothing happens.
If i prefill the file with abcd, abcd is printed instantly after programm start, but again I can’t echo something to the testfile.
Isn’t it possible to redirect stdin in this way?
2
Answers
I think you can do it using
getchar
like this:or using
read
like this:However, you need to append to the file using
>>
like:You can also use heredoc
<<
associated with redirection into a file like this :In this exemple I use
>>
to add line at the end of the file but you can overwrite it with>