When the device was testing power off and on, it was found that the content of a json file was missing. The function to operate it is as follows:
/* 将json写入文件 */
FILE *pf = fopen(file_path,"w+");
if( pf == NULL)
{
log_e("open %s fail: %s", file_path, strerror(errno));
goto release_resources;
}
log_d("write file %s", cjson_str);
fwrite(cjson_str,strlen(cjson_str), 1, pf);
fflush(pf);
The result was beyond my expectation. The left side of the picture below shows a normal file, and the right side shows an error file. They are the same size, but the content of the file on the right side is all 0.
enter image description here
My understanding of the fflush function is that it writes all unwritten data to the file pointed to by pf. If the power is off, the file size will be 0, or only part of it will be written. Is my understanding of the fflush function wrong? I am currently trying to figure out if the power is off during the process of writing a file, will the situation shown in the figure occur? Why is this the case?
Note
My device uses NAND flash, and I will also add fsync() to write it to flash immediately, and add a form of data backup.
thanks!
work aaron is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.