简体   繁体   中英

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

So, I'm trying to write ac 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;
        }
    }
}

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 .

If you have another input piped in, then that will replace stdin (the terminal) with that input file. If you'd like to get input from the terminal, I'd suggest taking the file in as a parameter rather than a pipe, and then you can use stdin as normal.

Here's an example.

Execution:

./a.out foo.txt

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM