#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#define MAX_FILES 1024
#define MAX_LINE_LEN 256
// 判断字符串是否以指定后缀结尾
int ends_with(const char *str, const char *suffix) {
if (!str || !suffix) return 0;
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr) return 0;
return strcmp(str + lenstr - lensuffix, suffix) == 0;
}
// 比较文件名用于qsort排序
int cmp_filename(const void *a, const void *b) {
const char **fa = (const char **)a;
const char **fb = (const char **)b;
return strcmp(*fa, *fb);
}
// 解析_cfg.txt文件内容
void Parse_cfg_data(const char *fullpath) {
FILE *fp = fopen(fullpath, "r");
if (!fp) {
perror("打开_cfg.txt文件失败");
return;
}
char line[MAX_LINE_LEN];
int lineNum = 0;
int cfg_data_lines = 0;
// 先读前三行,第三行会有 "Job line X"
while (lineNum < 3 && fgets(line, sizeof(line), fp)) {
lineNum++;
if (lineNum == 3) {
// 查找"Job line "后面的数字
char *p = strstr(line, "Job line");
if (p) {
// 跳过"Job line "
p += strlen("Job line");
while (*p == ' ' || *p == '\t') p++;
cfg_data_lines = atoi(p);
} else {
printf("文件 %s 第三行无Job line信息\n", fullpath);
fclose(fp);
return;
}
}
}
if (cfg_data_lines == 0) {
printf("文件 %s 未找到有效的cfg数据行数\n", fullpath);
fclose(fp);
return;
}
// 继续读取cfg_data_lines行CFG数据
int read_lines = 0;
while (read_lines < cfg_data_lines && fgets(line, sizeof(line), fp)) {
read_lines++;
char prefix[16];
unsigned int addr;
uint64_t data;
// 注意lx和llx的区别,如果你的编译器uint64_t实际是unsigned long long,要用llx
if (sscanf(line, "%s 0x%x 0x%llx", prefix, &addr, &data) == 3) {
printf("0x%016llx\n", data);
} else {
printf("格式错误: %s\n", line);
}
}
fclose(fp);
}
// 遍历目录,获取所有文件名并排序
void Parse_TV(const char *pathName) {
DIR *dir = opendir(pathName);
if (!dir) {
perror("打开目录失败");
return;
}
struct dirent *entry;
char *fileList[MAX_FILES];
int fileCount = 0;
// 读取文件名列表
while ((entry = readdir(dir)) != NULL) {
// 过滤掉.和..
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 只存文件名,不包含路径
if (fileCount >= MAX_FILES) {
printf("文件数量超过最大限制%d\n", MAX_FILES);
break;
}
fileList[fileCount] = strdup(entry->d_name);
if (!fileList[fileCount]) {
perror("内存分配失败");
break;
}
fileCount++;
}
closedir(dir);
// 排序
qsort(fileList, fileCount, sizeof(char *), cmp_filename);
// 遍历文件,找*_cfg.txt文件解析
for (int i = 0; i < fileCount; i++) {
if (ends_with(fileList[i], "_cfg.txt")) {
// 拼接完整路径
char fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", pathName, fileList[i]);
printf("解析文件: %s\n", fullpath);
Parse_cfg_data(fullpath);
}
free(fileList[i]);
}
}
int main() {
const char *pathName = "/mnt/hgfs/VM_Share/XX_TV";
Parse_TV(pathName);
return 0;
}
08-26
1035

被折叠的 条评论
为什么被折叠?



