从文件读取的问题。读取()系统调用

Problems with reading from file. read() syscall

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

Use: Ubuntu 16.04.

gcc version 5.4.0.

kernel: 4.15.0-43-generic

尝试过:

add fsync call after writing data.

#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;
}

预期: 应该写入和读取数据 from/to 文件。

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

写入后需要倒回文件。

修复:

lseek(fd, 0, SEEK_SET);

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

修复:

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