C - 读取系统调用未检测到文件结尾



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

#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,读来处理这个,打开只是为了测试,我不明白它为什么要这样做,通常读返回那个文件中读取的字节数,如果它到达文件末尾,则返回0,所以看到这个有点奇怪。

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

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

若要限制打印缺少空字符的字符数组,请使用精度修饰符。 这将打印字符数组,最多打印这么多字符或空字符 - 这是第一个。

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

调试提示:使用哨兵打印文本,以清楚地指示每次打印的结果。

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

除了chux的答案提供的非常优雅的解决方案之外,您还可以在打印之前显式终止缓冲区(并且仅将其设置为C-"字符串"):

while ((rd = read(fd, buffer, READ_SIZE-1)) > 0) /* read one less, to have a spare 
                                                    char available for the `0`-terminator. */
{
  buffer[rd] = '';
  printf("'%s'", buffer);
}

最新更新