Search code examples
c++linuxfile-iofcntlunistd.h

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.


Solution

  • From 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.

    From 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:

    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.