在 Debian(或其他 Linux 系统)下使用 opendir() / readdir() 处理中文目录或中文文件名,本质上不是 opendir 本身的问题,而是编码问题。下面给你一个清晰、可用的说明和示例。
✅ Linux 文件系统里面,文件名是以“字节序列”存储的
✅ Debian 默认使用 UTF-8 编码(如 zh_CN.UTF-8)
✅ 只要你的程序:
那么 opendir() / readdir() 不需要任何特殊处理,中文完全正常。
❌ 常见错误:
mkdir 测试目录
touch 测试目录/中文文件.txt
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir("测试目录");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
✅ 编译运行:
gcc test.c -o test
./test
输出:
.
..
中文文件.txt
locale
应该看到:
LANG=zh_CN.UTF-8
LC_CTYPE=zh_CN.UTF-8
sudo dpkg-reconfigure locales
勾选:
zh_CN.UTF-8
并设为默认。
更推荐(C++17+):
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
for (auto &p : fs::directory_iterator("测试目录")) {
std::cout << p.path().string() << std::endl;
}
}
编译:
g++ test.cpp -std=c++17 -o test
| 问题 | 原因 | 解决 |
|---|---|---|
| 中文乱码 | 源码是 GBK | 转 UTF-8 |
| 打不开目录 | 路径编码不对 | 用 UTF-8 字符串 |
| 终端乱码 | 终端非 UTF-8 | 改终端编码 |
| 想用 wchar_t | 没必要 | Linux 下用 UTF-8 即可 |
✅ 不需要:
❌ 需要:
wcwidth)如果你愿意,可以告诉我:
我可以直接给你对应的最佳实践代码。