-1

I am doing Linux system programming using Visual Studio and deploying it to VirtualBox VM. Here, I have create an array of 10 unsigned long element of i*i value. Then, I wrote the array to 'sample.bin' file. However, while retrieving the array, I get garbage values or zero.

#include <cstdio>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main() {

    unsigned long elements[10];
    for (int i = 0; i < 10; i++) {
        elements[i] = (unsigned long)(i * i);
    }

    int fileHandle = open("sample.bin", O_CREAT | O_TRUNC | O_RDWR | O_APPEND, 0777);

    int dataToFile = write(fileHandle, elements, 10 * sizeof(unsigned long));
    
    unsigned long readBuffer[10];
    
    int dataFromFile = read(fileHandle, readBuffer, 10 * sizeof(unsigned long));
    
    for (int i = 0; i < 10; i++) {

        printf("%d\t", readBuffer[i]);

    }

    return 0;
}

I tried the following:

  1. I tried modifying 'write' function as write(fileHandle, &elements, 10 * sizeof(unsigned long));, but it didn't work. The same goes for 'read' function.

  2. I tried '%lu' as format specifier, still didn't work

Jawad
  • 3
  • 3
  • 4
    You probably have to navigate to the beginning of the file before switching from write to read, see `lseek` – yeputons May 14 '23 at 21:12
  • 1
    Why have you ignored the result `dataFromFile`? If you inspect it you will see the issue. – 273K May 14 '23 at 21:22

1 Answers1

0

As @yeputons mentioned in a comment, you will need to reset the file handle before you read the data. E.g. by using lseek.

The code looks like it might be an exercise, where you are practicing using the system calls. In that case, you obviously have to use the calls you are learning to use. Otherwise, you should probably use fwrite/fread or C++ streams instead.

See the question What are the main differences between fwrite and write? for information about the difference between write and fwrite.

Jørgen Fogh
  • 7,516
  • 2
  • 36
  • 46