【问题标题】:Problems with reading from file. read() syscall从文件读取的问题。 read() 系统调用
【发布时间】:2019-01-28 18:00:20
【问题描述】:

当我尝试从文件中读取数据并打印时,printf 将一个空字符串打印到终端。

使用:Ubuntu 16.04。

gcc 版本 5.4.0。

内核:4.15.0-43-generic

试过了:

写入数据后添加fsync调用。

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

#define SIZE 6

int main()
{
   int ret = -1;
   char buffer[SIZE] = { 0 };
   int fd = open("data.txt", O_CREAT | O_RDWR, 0666);

   if (fd < 0)
   {
   perror("open()");
   goto Exit;
   }

   if (write(fd, "Hello", 5) < 0)
   {
       perror("write()");
   goto Exit;
   }

   fsync(fd);

   if (read(fd, buffer, SIZE - 1) < 0)
   {
   perror("read()");
   goto Exit;
   }

   printf("%s\n", buffer);
   ret = 0;

   Exit:
        close(fd);
        return ret;
}

预期:应该在文件中写入和读取数据。

实际: 数据写入文件。读取数据后,printf 打印一个空字符串。

【问题讨论】:

  • 您的错误检查已损坏。你不知道read是否成功。
  • @EugeneSh。 buffer 初始化为零。

标签: c unix glibc


【解决方案1】:

写入后,您需要倒带文件。

修复:

lseek(fd, 0, SEEK_SET);

请注意,通常您不需要对读取缓冲区进行零初始化,这是浪费时间。您应该使用read/recv 的返回值来确定接收到的数据的长度,并在必要时手动对其进行零终止。

修复:

ssize_t r = read(fd, buffer, SIZE - 1);
if (r < 0)
    // handle error
buffer[r] = 0; // zero-terminate manually.
printf("%s\n", buffer);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多