使用opendir()打开Windows有效目录报错“No such file or directory”求助
问题:WSL环境下C代码无法访问Windows D盘目录
在Windows 10的WSL环境中测试一段C代码,编译命令为cc -std=c11 -o sample sample.c,编译无错误,代码文件位于D:\TopFolder\Test。目标文件夹存在且权限设置正常,但尝试访问D盘根目录或D:\TopFolder均失败,期望代码能列出指定路径下的所有文件和目录。
原代码如下:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> int main() { //const char *path = "D:\\TopFolder"; // 同样无法工作 const char *path = "D:\\\"; // 指定目录路径 DIR *directory; struct dirent *entry; // 打开目录 directory = opendir(path); if (directory == NULL) { printf("尝试打开目录: %s\n", path); perror("打开目录失败"); return EXIT_FAILURE; // 无法打开则退出 } // 读取目录项 printf("%s 的内容:\n", path); while ((entry = readdir(directory)) != NULL) { // 跳过 "." 和 ".." 项 if (entry->d_name[0] != '.') { printf("%s\n", entry->d_name); } } // 关闭目录 closedir(directory); return EXIT_SUCCESS; // 成功退出 }
执行icacls d:返回的权限信息(供参考):
d: BUILTIN\Administrators:(F) BUILTIN\Administrators:(OI)(CI)(IO)(F) NT AUTHORITY\SYSTEM:(F) NT AUTHORITY\SYSTEM:(OI)(CI)(IO)(F) NT AUTHORITY\Authenticated Users:(M) NT AUTHORITY\Authenticated Users:(OI)(CI)(IO)(M) BUILTIN\Users:(RX) BUILTIN\Users:(OI)(CI)(IO)(GR,GE)
解决方法
- WSL路径格式错误:WSL采用类Unix路径规则,Windows的D盘在WSL中被挂载到
/mnt/d/路径下,D:\TopFolder对应的WSL路径应为/mnt/d/TopFolder。原代码使用Windows风格的路径D:\\或D:\\TopFolder,WSL无法识别。 - 字符串转义错误:原代码中
const char *path = "D:\\\";存在语法错误,末尾的反斜杠未正确转义,正确写法应为"D:\\",但即使修正这个问题,路径格式仍不符合WSL的要求。
修改后的代码示例:
#include <stdio.h> #include <stdlib.h> #include <dirent.h> int main() { const char *path = "/mnt/d/TopFolder"; // WSL格式的目标路径 // 若访问D盘根目录则写为:const char *path = "/mnt/d/"; DIR *directory; struct dirent *entry; directory = opendir(path); if (directory == NULL) { printf("尝试打开目录: %s\n", path); perror("打开目录失败"); return EXIT_FAILURE; } printf("%s 的内容:\n", path); while ((entry = readdir(directory)) != NULL) { if (entry->d_name[0] != '.') { printf("%s\n", entry->d_name); } } closedir(directory); return EXIT_SUCCESS; }
若修改路径后仍存在权限问题,可检查WSL的挂载权限:默认挂载时普通用户已有读写权限,如需调整可修改/etc/wsl.conf配置文件,添加以下内容后重启WSL:
[automount] enabled = true options = "metadata,umask=0022,fmask=0133" mountFsTab = false
内容的提问来源于stack exchange,提问作者rise.ashok
相关产品推荐
相关产品推荐

