gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:37:59 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com