在 CentOS(Linux) 下使用 readdir(一般是 C 语言的 readdir() / readdir_r())时,编码问题核心在于文件名在文件系统中的编码方式,而不是 readdir 本身。
下面分点说明。
readdir() 返回的是 原始字节,不是“字符”例如:
struct dirent *entry;
entry->d_name // 这是 byte[],可能是 UTF-8、GBK、ISO-8859-1 等
✅ 是否正确,取决于:
现代 CentOS(7/8/Stream):
locale
通常看到:
LANG=en_US.UTF-8
LC_CTYPE=UTF-8
✅ 表示 文件系统一般使用 UTF-8
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
?不要“转换 readdir”,而是:
iconv 转换编码#include <iconv.h>
#include <string.h>
// GBK -> UTF-8
示例(简化):
iconv_t cd = iconv_open("UTF-8", "GBK");
iconv(cd, &in, &inlen, &out, &outlen);
struct dirent entry;
struct dirent *result;
readdir_r(dir, &entry, &result);
entry.d_name 同样是 原始字节
✅ 推荐方案:
❌ 不推荐:
for (int i = 0; entry->d_name[i]; i++)
printf("%02X ", (unsigned char)entry->d_name[i]);
locale
iconv -f GBK -t UTF-8 file
CentOS 的 readdir 不“编码”,它只返回字节;是否正确显示,取决于文件系统编码和程序/终端是否一致(通常应为 UTF-8)。
如果你愿意,可以告诉我:
我可以给你更针对性的解决方案。