linux 来自 unistd.h 的 read() 函数对我不起作用:(

linux read() function from unistd.h doesn't work for me :(

我尝试了所有我能想到的方法,但出于某种原因,它没有将文件中的数据存储到“数据”中,但文件中有写入的数据。

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{
   char data[69]=" ";
   int fd = open("./MyFile.txt", O_RDWR | O_CREAT | O_SYNC | O_RSYNC);
   write(fd, "HELLO", 5);
   read(fd, data, 5);

   cout << data << endl;

return 0;
}

你们能帮帮我吗?我正在尝试学习文件 I/O,但我不知道它是 O_RDWR 还是这里有什么问题。

来自man write

For a seekable file (i.e., one to which lseek(2) may be applied, for example, a regular file) writing takes place at the current file offset, and the file offset is incremented by the number of bytes actually written.

来自man read

On files that support seeking, the read operation commences at the current file offset, and the file offset is incremented by the number of bytes read.

您需要 seek 回到文件的开头 write,如果您想要然后 read 您刚刚写的内容:

lseek(fd, 0, SEEK_SET);

始终阅读和研究您使用的功能的文档,尤其是当它们未按照您的预期进行时。

文件描述符位置在write(2)之后的末尾。要read(2)从头开始,需要将fd倒回头。

你可以用 lseek:

   write(fd, "HELLO", 5);
   lseek(fd, 0, SEEK_SET);
   read(fd, data, 5);

您还应该为所有这些系统调用(打开、读取、写入、lseek)添加错误检查。