简体   繁体   English

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

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

I tried everything i could think of but for some reason it doesn't store the data from the file to "data", but the file has the written data.我尝试了我能想到的一切,但由于某种原因,它不会将文件中的数据存储到“数据”中,但文件中有写入的数据。

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

Could you guys please help me.你们能帮帮我吗? I'm trying to learn file I/O and I don't know if it's the O_RDWR or whatever that is wrong here.我正在尝试学习文件 I/O,但我不知道是 O_RDWR 还是这里有什么问题。

From man write :man write

For a seekable file (ie, 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.对于可查找文件(即,可以应用 lseek(2) 的文件,例如常规文件),写入发生在当前文件偏移量处,并且文件偏移量增加实际写入的字节数。

From man read :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.在支持查找的文件上,读取操作从当前文件偏移量开始,文件偏移量增加读取的字节数。

You need to seek back to the start of the file after your write , if you want to then read what you just wrote:你需要在你write之后回到文件的开头,如果你想read你刚刚write的内容:

lseek(fd, 0, SEEK_SET);

Always read and study the documentation for the functions that you use, particularly when they're not doing what you thought they would do.始终阅读和研究您使用的函数的文档,特别是当它们没有按照您的想法执行时。

The file descriptor position is at the end after the write(2) .文件描述符 position 在write(2)之后位于末尾。 To read(2) from the beginning, you need rewind the fd back to the beginning.要从头开始read(2) ,您需要将 fd 倒回到开头。

You can do with lseek :您可以使用lseek

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

Also you should add error checks for all these system calls (open, read, write, lseek).此外,您应该为所有这些系统调用(open、read、write、lseek)添加错误检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM