У меня есть программа на C, которая пытается читать до 1024 байт от stdin.Почему read() возвращает только первую строку 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;
}
Я скомпилировать и запустить его:
$ cat testfile.txt
hello
world
$ gcc -Wall -std=c99 oneline.c
$ cat testfile.txt | ./a.out
bytes read: 6
program: hello
Почему read()
только заполнить мой буфер с первой строкой ввода? Я не вижу ссылок на новые строки в man 3 read
.
Я предполагаю, что это тест, но на всякий случай всегда проверяйте возвращаемое значение 'malloc' –
Ваш пример читает 12 байтов и печатает обе строки для меня. – pilcrow