【发布时间】:2017-01-13 18:53:28
【问题描述】:
我正在尝试创建一个函数,该函数使用可以随时更改的特定读取大小读取整个文件,但是读取系统调用不会将字符正确存储在缓冲区中,到目前为止我只是想像这样打印到文件末尾:
#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到达文件末尾,所以看到这个有点奇怪。
【问题讨论】:
-
由于
while()语句中的括号不平衡,您的程序无效且无法编译。缺少括号的位置会影响代码的含义。 -
在使用
printf之前忘记NULL终止缓冲区 -
@user161151
NULL是 空指针常量。当然,您的意思是 null 字符 或'\0'。 -
@chux 我当然愿意。
-
@James 如果您的新代码有与此相同的问题(使用
%s打印缺少空字符的字符数组),那么新代码也会被捕获在 未定义行为 i> (UB) 陷阱。它可能今天有效,明天失败。