c - 为什么 read() 只返回 stdin 的第一行?

标签 c posix

我有一个 C 程序,它试图从 stdin 读取多达 1024 个字节。

#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 中看不到任何对换行符的引用.

最佳答案

来自 linux 手册页 read(2) 手动的:

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, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.



所以这是因为您正在从管道中读取数据。显而易见的解决方案是继续阅读直到 0被退回。

关于c - 为什么 read() 只返回 stdin 的第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850940/

相关文章:

c - 如何用C语言求解100^1000?

c - 如何检查线程安全函数?

c - POSIX 生产者-消费者

linux - 用 c 实现的简单 shell 程序中的输入输出文件重定向和 shell 管道

c++ - O_DIRECT 与 AIO_RAW

c - 如何限制 C/POSIX 中函数的执行时间?

c - 如何在 Linux 上用 C 语言产生声音?

c - 在zlib.h中使用inflate在client中使用server发送的解压包时初始化z_stream.avail_out的值

c - 是否可以使用 GCC 编译器在 Linux 中发出 BEEP 声音?

c - forks和pipes实现linux编译器