读取系统调用不检测文件结束
read system call doesn't detect end of file
我正在尝试创建一个函数,该函数使用可以随时更改的特定读取大小来读取整个文件,但是读取系统调用没有将字符正确存储在缓冲区中,到目前为止我只是尝试像这样打印到文件末尾:
#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 returns读取的字节数在该文件中,如果到达文件末尾则为 0,所以看到这个有点奇怪。
字符数组打印缺少空字符。这是 "%s"
.
的 UB
printf("%s", buffer); // bad
要限制打印缺少空字符的字符数组,请使用精度修饰符。这将打印字符数组最多那么多字符或空字符 - 以先到者为准。
// printf("%s", buffer);
printf("%.*s", rd, buffer);
调试提示:用标记打印文本,以清楚地指示每次打印的结果。
printf("<%.*s>\n", rd, buffer);
除了 提供的非常优雅的解决方案之外,您还可以在打印之前显式终止缓冲区(这样只会使其成为 C-"string"):
while ((rd = read(fd, buffer, READ_SIZE-1)) > 0) /* read one less, to have a spare
char available for the `0`-terminator. */
{
buffer[rd] = '[=10=]';
printf("'%s'", buffer);
}
我正在尝试创建一个函数,该函数使用可以随时更改的特定读取大小来读取整个文件,但是读取系统调用没有将字符正确存储在缓冲区中,到目前为止我只是尝试像这样打印到文件末尾:
#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 returns读取的字节数在该文件中,如果到达文件末尾则为 0,所以看到这个有点奇怪。
字符数组打印缺少空字符。这是 "%s"
.
printf("%s", buffer); // bad
要限制打印缺少空字符的字符数组,请使用精度修饰符。这将打印字符数组最多那么多字符或空字符 - 以先到者为准。
// printf("%s", buffer);
printf("%.*s", rd, buffer);
调试提示:用标记打印文本,以清楚地指示每次打印的结果。
printf("<%.*s>\n", rd, buffer);
除了
while ((rd = read(fd, buffer, READ_SIZE-1)) > 0) /* read one less, to have a spare
char available for the `0`-terminator. */
{
buffer[rd] = '[=10=]';
printf("'%s'", buffer);
}