C Programming: How to read terminal input data if piping is from stdin?

So, I'm trying to write an ac program that reads the input into the program (via stdin), but I also need to be able to read input from the terminal (so I obviously can't read it from stdin), How do I do this? I am trying to open another file descriptor for / dev / tty as follows:

int see_more() { char response; int rd = open("/dev/tty", O_RDWR); FILE* reader = fdopen(rd, "r"); while ((response = getc(reader)) != EOF) { switch (response) { case 'q': return 0; case ' ': return 1; case '\n': return -1; } } } 

But this leads to a segmentation error.

Here is the version that works. Thanks for helping everyone :)

 int see_more() { char response; while (read(2, &response, 1)) { switch (response) { case 'q': return 0; case ' ': return 1; case '\n': return -1; } } } 
+4
source share
2 answers

The problem is that you are using single quotes instead of double quotes:

 FILE* reader = fdopen(rd, 'r'); 

it should be

 FILE* reader = fdopen(rd, "r"); 

Here is the fdopen prototype:

 FILE *fdopen(int fildes, const char *mode); 

It expects a char* , but you pass it a char .

+3
source

If you have a different input entering the system, then this will replace stdin (terminal) with this input file. If you want to get input from the terminal, I would suggest taking the file as a parameter, not a channel, and then you can use stdin as usual.

Here is an example.

Execution:

 ./a.out foo.txt 

the code:

 int main(int argc, char* argv[]) { if (argc >= 2) { char* filename = argv[1]; } else { // no filename given return 1; } // open file and read from that instead of using stdin // use stdin normally later } 
0
source

Source: https://habr.com/ru/post/1402338/


All Articles