Cat Cat - 5 days ago 8
C Question

Unistd read() maximum size

In the following snippet, no matter how long of an input I put in (EDIT: I'm copy and pasting in a random string), say a string with 9998 characters, read() stops when i = 4095. It states it read in an EOF character, but my string does not have an EOF character (for example I tried a string of 9998 'a's). The return value also suggests there is no error from read(). Why does read() only read in only 4095 bytes?



#include <unistd.h>
#include <stdio.h>

int main() {
char temp;
char buf[10000];
int i = 0;
while(read(STDIN_FILENO, &temp, 1) > 0) {
buf[i] = temp;
i++;
}
printf("%d\n", i);
}


Edit: To clarify, read() doesn't literally state that it read in an EOF character, per https://linux.die.net/man/2/read read() returns 0 when it moves past the EOF.

Answer

You're most likely seeing the terminal buffer limit -- terminals can only read a limited number of characters on a single line, and if you type in more than that (or simulate typing with a pseudo-terminal) without entering an NL, EOL, or EOL2 character, you'll get an error, which the terminal indicates with an EOF (read returning 0).

Comments