我需要为带有 C 和 FATFS 的 STM32 MCU 编写一个程序,以在未知数量的文件中找到最新的文件。文件名包含它们的创建日期,文件名中的数字用“_”分隔。例如:oil_sensor_22_07_20_13_15.csv
我编写了一个代码来从文件中提取日期和时间并计算它们的时间差。但我不知道如何在所有文件中找到最新的文件。
我包括计算两个文件之间的时间差的代码和在两个文件中找到最新文件的代码。
计算两个文件名时间差的函数:
double calc_passed_secs(char * name_str_01, char * name_str_02 ){
struct tm tm_struct_1,tm_struct_2;
time_t time_t_1,time_t_2;
// Returns first token
char* token = strtok(name_str_01, "_");
token = strtok(NULL, "_");
token = strtok(NULL, "_");
tm_struct_1.tm_mday = atoi(token);
token = strtok(NULL, "_");
tm_struct_1.tm_mon = atoi(token);
token = strtok(NULL, "_");
tm_struct_1.tm_year = atoi(token);
token = strtok(NULL, "_");
tm_struct_1.tm_hour = atoi(token);
token = strtok(NULL, "_");
token = strtok(token, ".");
tm_struct_1.tm_min = atoi(token);
tm_struct_1.tm_sec = 0;
// Returns first token
token = strtok(name_str_02, "_");
token = strtok(NULL, "_");
token = strtok(NULL, "_");
tm_struct_2.tm_mday = atoi(token);
token = strtok(NULL, "_");
tm_struct_2.tm_mon = atoi(token);
token = strtok(NULL, "_");
tm_struct_2.tm_year = atoi(token);
token = strtok(NULL, "_");
tm_struct_2.tm_hour = atoi(token);
token = strtok(NULL, "_");
token = strtok(token, ".");
tm_struct_2.tm_min = atoi(token);
tm_struct_2.tm_sec = 0;
double seconds = difftime(mktime(&tm_struct_1),mktime(&tm_struct_2));
printf("\r\nTime difference in seconds: %.f\r\n",seconds);
return seconds;
}
以及找到最新文件的程序(程序没有给出预期的结果)。
char newest_log_file[128];
char oldest_log_file[128];
char first_log_file [128];
char second_log_file [128];
char first_log_file_cpy [128];
char second_log_file_cpy [128];
//char printf_buff [128];
// find first file
fr = f_findfirst(&dj, &fno1, "", "oil_sensor_*.csv");
strcpy( first_log_file,fno1.fname);
strcpy(first_log_file_cpy, first_log_file);
if (!fno1.fname[0]) {
bool make_first_log_file = true;
}
if (fno1.fname[0]) {
fr = f_findnext(&dj, &fno1);
}
if (fno1.fname[0]) {
strcpy(second_log_file,fno1.fname);
strcpy(second_log_file_cpy, second_log_file);
}
printf("\r\nFirst Log File: %s\r\n", first_log_file);
printf("\r\nSecond Log File: %s\r\n", second_log_file);
double seconds = calc_passed_secs(first_log_file , second_log_file);
if (seconds < 0){
strcpy(newest_log_file, second_log_file_cpy);
}
if (seconds > 0) {
strcpy(newest_log_file, first_log_file_cpy);
}
printf("\r\nnewest file: %s\r\n", newest_log_file);
do {
f_findnext(&dj,&fno1);
strcpy(first_log_file, fno1.fname);
strcpy(first_log_file_cpy, first_log_file);
f_findnext(&dj,&fno1);
strcpy(second_log_file,fno1.fname);
strcpy(second_log_file_cpy, second_log_file);
printf("\r\nFirst Log File: %s\r\n", first_log_file);
printf("\r\nSecond Log File: %s\r\n", second_log_file);
if (seconds < 0){
strcpy(newest_log_file, second_log_file_cpy);
}
if (seconds > 0) {
strcpy(newest_log_file, first_log_file_cpy);
}
printf("\r\nnewest file: %s\r\n", newest_log_file);
seconds = calc_passed_secs(first_log_file, second_log_file);
} while (fr == FR_OK && fno1.fname[0]);
f_closedir(&dj);