终极解决方案(任选其一)
方案1️⃣:添加宏定义(推荐)
#define _GNU_SOURCE // 必须放在文件最顶部(所有#include之前)
#include <dirent.h> // 提供DT_REG定义
// 你的原始代码完全不变
if (entry->d_type == DT_REG && is_audio_file(entry->d_name)) {
int path_len = strlen("music/") + strlen(entry->d_name) + 1;
player.audio_list[idx] = malloc(path_len);
snprintf(player.audio_list[idx], path_len, "music/%s", entry->d_name);
player.audio_names[idx] = strdup(entry->d_name);
printf("加载音频 %d: %s\n", idx, player.audio_list[idx]);
idx++;
}
方案2️⃣:编译时添加flag(不修改代码)
gcc -D_GNU_SOURCE your_program.c -o output
方案3️⃣:改用stat兼容写法
#include <sys/stat.h>
struct stat file_info;
if (stat(entry->d_name, &file_info) == 0 &&
S_ISREG(file_info.st_mode) && // 等价于DT_REG
is_audio_file(entry->d_name))
{
// 你原有的逻辑完全不变...
}
问题本质
现象 | 原因 | 解决方案 |
---|---|---|
DT_REG 报红 |
需要显式启用POSIX/GNU扩展 | 添加#define _GNU_SOURCE |
旧Linux/Unix兼容性 | 某些系统默认不暴露d_type |
改用stat() 方案 |
IDE误报(如VSCode) | 头文件索引问题 | 实际编译能通过即可忽略 |
验证是否解决
-
在代码中打印
DT_REG
值:printf("DT_REG=%d\n", DT_REG); // 正常应输出8
-
如果使用方案1/2后仍报错,说明你的系统确实不支持,请改用方案3(stat)。
选择方案1或2可以保持你的代码 一字不改 直接解决问题。