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;
}
}
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With