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:
I tried modifying 'write' function as
write(fileHandle, &elements, 10 * sizeof(unsigned long));
, but it didn't work. The same goes for 'read' function.I tried '%lu' as format specifier, still didn't work