Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming: How do I read terminal input if piping from stdin?

Tags:

c

linux

stdio

So, I'm trying to write a c program that reads input piped into the program (through stdin), but I also need to be able to read input from the terminal (so I obviously can't read it from stdin). How would I do that? I'm trying to open another file handle to /dev/tty like this:

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 that results in a segmentation fault.

Here's the version that works. Thanks for everyone's help :)

int see_more() {
    char response;
    while (read(2, &response, 1)) {
        switch (response) {
            case 'q':
                return 0;
            case ' ':
                return 1;
            case '\n':
                return -1;
        }
    }
}
like image 933
David Mulder Avatar asked Oct 08 '22 08:10

David Mulder


1 Answers

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

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

should be

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

Here is the prototype of fdopen:

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

It expects a char*, but you're passing it a char.

like image 115
Adam Zalcman Avatar answered Oct 12 '22 22:10

Adam Zalcman