gpt4 book ai didi

c - 读取系统调用不检测文件结束

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:14 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,该函数使用可以随时更改的特定读取大小来读取整个文件,但是读取系统调用没有将字符正确存储在缓冲区中,到目前为止我只是在尝试像这样打印到文件末尾:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

# define READ_SIZE (42)

int main(int argc, char **argv)
{
int fd;
int rd;
char *buffer;

buffer = malloc(READ_SIZE);
fd = open(argv[1], O_RDONLY);
while ((rd = read(fd, buffer, READ_SIZE)) > 0)
{
printf("%s", buffer);
}
return (0);
}

这是我正在尝试读取的文件:

test1234
test123
test1
test2
test3
test4
test

这是我的程序的输出:

test123
test12
test1
test2
test3
test4
testest123
test12
test1
test2
test3
test4
tes

我只能用malloc,read来处理这个,open只是为了测试,我不明白为什么要这样做,通常read返回那个文件中读取的字节数, 如果它到达文件末尾则为 0,所以看到这个有点奇怪。

最佳答案

字符数组的打印缺少空字符。这是带有 "%s" 的 UB。

printf("%s", buffer);  // bad

要限制打印缺少空字符的字符数组,请使用精度修饰符。这将打印字符数组,最多为多个字符或一个空字符 - 以先到者为准。

// printf("%s", buffer);
printf("%.*s", rd, buffer);

调试提示:打印带有标记的文本,以清楚地指示每次打印的结果。

printf("<%.*s>\n", rd, buffer);

关于c - 读取系统调用不检测文件结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41641557/

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