C++中使用readdir()获取文件完整路径的实现疑问
如何打印目录中文件的完整路径?
需求是输出目录下txt文件的完整路径,预期输出示例:C:\Users\Gadr\Desktop\Text,但现有代码仅输出文件名前缀Text。
用户当前代码:
di = opendir("C:\\Users\\Gadr\\Desktop"); //specify the directory name while ((dir = readdir(di)) != NULL) { ptr1 = strtok(dir->d_name, "."); ptr2 = strtok(NULL, "."); if (ptr2 != NULL) { retn = strcmp(ptr2, "txt"); if (retn == 0) { printf("%s\n", ptr1); } } }
问题根源
代码仅提取了dir->d_name(纯文件名)的前缀部分,完全没有拼接目录路径,自然无法输出完整路径。此外,用strtok分割文件名判断后缀存在缺陷——如果文件名包含多个.(如note.v2.txt),会误判后缀。
修正方案
以下是调整后的代码,实现完整路径输出,并修复后缀判断的问题:
#include <stdio.h> #include <dirent.h> #include <string.h> #include <stdlib.h> int main() { const char *target_dir = "C:\\Users\\Gadr\\Desktop"; DIR *dir_stream = opendir(target_dir); // 检查目录是否成功打开 if (!dir_stream) { perror("Failed to access directory"); return 1; } struct dirent *entry; char full_file_path[256]; // 缓冲区大小可根据实际路径长度调整 while ((entry = readdir(dir_stream)) != NULL) { // 跳过当前目录(.)和上级目录(..)的特殊条目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 安全拼接目录路径与文件名,生成完整路径 snprintf(full_file_path, sizeof(full_file_path), "%s\\%s", target_dir, entry->d_name); // 准确判断文件后缀是否为txt char *dot_pos = strrchr(entry->d_name, '.'); if (dot_pos != NULL && strcmp(dot_pos + 1, "txt") == 0) { // 若需要去掉.txt后缀(如预期输出的`C:\Users\Gadr\Desktop\Text`) char *path_no_ext = strdup(full_file_path); if (path_no_ext) { *strrchr(path_no_ext, '.') = '\0'; printf("%s\n", path_no_ext); free(path_no_ext); // 释放动态分配的内存 } else { // 内存分配失败时输出完整带后缀路径 printf("%s\n", full_file_path); } } } closedir(dir_stream); return 0; }
关键调整点
- 路径拼接:使用
snprintf将目标目录路径与文件名拼接,生成完整路径,避免缓冲区溢出风险。 - 特殊目录过滤:跳过
.和..,避免生成无效路径。 - 后缀判断优化:用
strrchr查找文件名中最后一个.,确保即使文件名含多个点也能正确识别后缀。 - 后缀截断处理:通过
strdup复制完整路径后截断后缀,实现预期的无后缀完整路径输出。
内容的提问来源于stack exchange,提问作者urbanc cladr
相关产品推荐
相关产品推荐

