Reputation: 31161
I have a C program that tries to read up to 1024 bytes from stdin.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int MAX_SIZE = 1024;
char *program = malloc(sizeof(char) * MAX_SIZE);
int STDIN_FD = 0;
int return_code = 0;
int bytes_read = read(STDIN_FD, program, MAX_SIZE);
if (bytes_read == -1) {
printf("Could not read from stdin");
return_code = 1;
} else {
printf("bytes read: %d\n", bytes_read);
program[bytes_read] = '\0';
printf("program: %s\n", program);
}
free(program);
return return_code;
}
I compile it and run it:
$ cat testfile.txt
hello
world
$ gcc -Wall -std=c99 oneline.c
$ cat testfile.txt | ./a.out
bytes read: 6
program: hello
Why does read()
only fill my buffer with the first line of input? I can't see any references to newlines in man 3 read
.
Upvotes: 4
Views: 633
Reputation: 53006
From linux man pages read(2)
manual:
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because
read()
was interrupted by a signal. On error, –1 is returned, anderrno
is set appropriately. In this case it is left unspecified whether the file position (if any) changes.
So it's because you are reading from a pipe. And the obvious solution is to keep reading until 0
is returned.
Upvotes: 4