在 CentOS 下,readdir()(以及 opendir()/readdir() 系列函数)本身是支持中文文件名的,前提是 文件系统的编码 和 程序的 locale 设置一致,通常应为 UTF-8。
下面分情况说明:
locale
正常应为:
LANG=zh_CN.UTF-8
LC_CTYPE=zh_CN.UTF-8
如果不是,可临时设置:
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
永久生效:
localectl set-locale LANG=zh_CN.UTF-8
#define _GNU_SOURCE
#include <dirent.h>
#include <stdio.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, ""); // 关键
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
✅ 编译:
gcc test.c -o test
✅ 终端必须是 UTF-8(如 xterm、ssh 客户端)
mount -o iocharset=utf8 /dev/sdb1 /mnt/usb
或 NTFS:
mount -t ntfs-3g -o iocharset=utf8 /dev/sdb1 /mnt/usb
使用 iconv:
iconv_t cd = iconv_open("UTF-8", "GBK");
| 现象 | 原因 |
|---|---|
中文变成 ?? |
locale 不是 UTF-8 |
| 中文乱码 | 文件系统是 GBK |
| 程序崩溃 | 未设置 setlocale |
| SSH 乱码 | 客户端编码不是 UTF-8 |
CentOS 的 readdir 完全支持中文,只要“文件系统 UTF-8 + 程序 locale UTF-8 + 终端 UTF-8”三者一致。
如果你有 具体场景(C 程序 / Python / Shell / SMB / NFS / U盘),可以告诉我,我可以给你更精确方案。