我在Linux操作系统上运行了一些C代码到便携设备中。我正在使用VRmagic系统,类似于BeagleBone等......)。
在这段代码中,我使用以下函数在txt文件中写入结果。
//globale definition
FILE *logfile;
const char *logpath = "/MY_DEVICE/log.txt";
const char *main_folder_result_path = "/MEASUREMENT_RESULTS/";
const char *all_measurement_results_file_name = "all_computation_data.txt";
void save_to_log_file(const char *logpath,const char *message){
#ifdef savealllog
logfile = fopen(logpath,"a"); //logpath = "/MY_DEVICE/log.txt";
fprintf(logfile,"%s",message);
fclose(logfile);
#endif
#ifdef printalloutput
printf("%s",message);
#endif
}
void append_all_measurement_file(){
char buff[255];
char filename[255];
save_to_log_file(logpath," Appending all measurement file...");
sprintf(filename,"%s%s",main_folder_result_path,all_measurement_results_file_name);
//here after we create the header if the file does not exist already
FILE *pFile_all_measurement_results = fopen(filename, "r"); //lets try to read the file
if (pFile_all_measurement_results == NULL){ // if file does not exist
pFile_all_measurement_results = fopen(filename, "w");
fprintf(pFile_all_measurement_results,"date-time S_type Part_name batch count abs value_1 value_2 value_3 value_4\n");
fclose(pFile_all_measurement_results);
}
else{
fclose(pFile_all_measurement_results); //if file does exist then we have to close it here
}
//here after we are going to write results
pFile_all_measurement_results = fopen(filename, "a"); //lets open the file in append mode
fprintf(pFile_all_measurement_results,"%s %s %s %d %d %d ",dateandtimetps.dt,measurement_type_str,Name_Str, batch_number,count_number,absolute_measurement_number);
fprintf(pFile_all_measurement_results,"%.03f ", value_1);
fprintf(pFile_all_measurement_results,"%.03f ", value_2);
fprintf(pFile_all_measurement_results,"%.03f ", value_3);
fprintf(pFile_all_measurement_results,"%.03f\n", value_4); //(there are a bit more in reality.....)
fclose(pFile_all_measurement_results); //we can now close the file
save_to_log_file(logpath,"done.\n");
}
99.9%的时间都没问题。 但是,随机地,我的文件中确实有一些NUL字符,当我关闭系统时会发生这种情况。
由于某种原因,看起来文件没有正确关闭或类似的东西......
当我拿到我的txt文件,并在我的计算机上用notepad ++打开它时,它看起来如下所示:
我可以确认设备已在第172行和第174行之间关闭。
非常感谢您的帮助
答案 0 :(得分:2)
在Unix系统上关闭文件并不意味着内容会立即写入磁盘;通常启用缓冲/缓存。
为了确保写入内容,您可以在写入和/或关闭操作后立即使用sync()
,这样可以最大程度地降低更新丢失的风险。
此外,我建议使用像 ext4 这样的日记文件系统(这可能不是USB笔等外部驱动器上的选项,但强烈建议所有系统和数据分区使用)。如果出现电源故障或崩溃,这不会使您免于数据丢失,但会避免出现与您遇到的不一致/部分写入一样的情况。