I have developped a C program (Linux), this program create a new file and write into, after that it reboots the PC.
After reboot, I have lost the file created by my program. When I deactivate reboot function, the file created by my program is still present.
This behaviour is seen with Linux: - OpenWrt (Backfire 10.03) on VirtualBox (filesystem ext2) - Linux (Ubuntu) (filesystem ext4)
Have you an explication for this behavior and how can I fix it?
#include <stdio.h>
#include <sys/reboot.h>
int main ()
{
FILE *pFile;
char mybuffer[80];
pFile = fopen ("/home/user/Desktop/example.txt","w");
if (pFile == NULL) perror ("Error opening file");
else
{
fputs ("test",pFile);
fclose (pFile);
}
rename("/home/user/Desktop/example.txt","/home/user/Desktop/example123.txt");
reboot(RB_AUTOBOOT);
return 0;
}
The man page for fclose says:
Note that fclose() only flushes the user space buffers provided by the C library. To ensure that the data is physically stored on disk the kernel buffers must be flushed too, for example, with sync(2) or fsync(2).
Which means that you need to call fsync before closing the file descriptor.