Estimated time: 25 minutes
You are currently processing an array composed of struct point
defined below. In this programme, you need to store the content of the entire array in a file to be able to reuse it later. Write a C function to write the array composed of struct point
into a file. The file may already exist or not. After the execution of the function, the file should only contain the array. If the file has to be created, the user who created it must have the permission to read it.
typedef struct point { int x; int y; int z; } point_t;
Use only open(2)
, close(2)
, mmap(2)
, munmap(2)
, msync(2)
, memcpy(3)
and ftruncate(3)
. You can only call memcpy(3)
once.
Hint : read carefully the man page of open(2) to manage all the cases mentionned above. Be sure to open the file with the appropriate rights.
Hint : msync(2) is a function that ensures that your modifications done in memory (so in the address returned by mmap) will also be saved in the file. Check the documentation to learn how to use it (pay attention to the flags). Call it before munmap() (or your modifications to the memory may be lost) !
Hint : The function ftruncate(3) is a function that you won't need to use frequently. However, this function is mandatory to pass this exercice ! In your code, you have to use it to extend the size of the file you opened. When you'll call open (with the appropriate flags to meet the requirements above), the size of the file will be set to zero. So, in order for the mmap function to work, you'll need to extend its size to the one you want by calling ftruncate. Read the documentation linked and use this trick BEFORE calling mmap !