The main function will be in an infinite loop reading the numbers that the user puts in the terminal and storing them on a buffer. My problem is that I need to read from terminal using this function:
read(int fd, void *buf, size_t count);
How can the file descriptor point to the terminal?! (I hope I'm not saying some barbarity)
Thanks in advance!
EDIT: I already took your advice, but something is missing. This is a small program that I wrote to test:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int buffer[5], i=0, j;
int main(){
for(j=0; j<5; j++) buffer[j] = 0;
while(i<5){
read(STDIN_FILENO, buffer, 8);
printf("->%d\n", buffer[i]);
i++;
}
return 0;
}
Outup:
1
->2609
2
->0
3
->0
4
->0
5
->0
Why this doesn't print the numbers that I inserted?
Your process has three file descriptors open since it has been spawned: STDIN_FILENO
, STDOUT_FILENO
, STDERR_FILENO
(0, 1, 2 respectively). These macros are defined in unistd.h
.
read(STDIN_FILENO, buff, bytes)
By default the program's standard input is on file descriptor 0.
If you really mean to read from the terminal, instead of standard input, you can open()
/dev/tty
.
stdin
is fd 0
,
stdout
is fd 1
, and
stderr
is fd 2
.
On POSIX you can use symbols like STDIN_FILENO
to represents the input of your application. But beware that the standard input is not always the terminal, especially when you redirect input/output via the shell.
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.