Reputation: 87
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?
Upvotes: 0
Views: 5933
Reputation: 36391
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.
Upvotes: 1
Reputation: 9980
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
.
Upvotes: 2
Reputation: 8494
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)
Upvotes: 2