使用C++17 filesystem库删除文件失败问题求助
解决WSL Debian环境下C++ 删除文件失败的问题
你的问题核心是WSL环境不识别Windows风格的路径格式,以下是具体解决步骤:
1. 替换为WSL兼容的路径
WSL中访问Windows本地文件系统必须用Linux风格路径:
- Windows的
C:\对应WSL里的/mnt/c/ - 路径分隔符用正斜杠
/而非反斜杠\
把代码中的路径修改为:
std::filesystem::remove("/mnt/c/Users/mypath/Desktop/cppRoulette/delete.txt");
注意将mypath替换成你实际的Windows用户名。
2. 添加错误检查定位问题
std::filesystem::remove会返回布尔值表示操作是否成功,建议加上错误信息输出,方便排查具体失败原因:
if (possibility == chamberNumber){ bool success = std::filesystem::remove("/mnt/c/Users/mypath/Desktop/cppRoulette/delete.txt"); if (success) { cout << "You're Dead " << possibility << endl; } else { cerr << "删除失败:" << std::filesystem::last_error().message() << endl; } }
这样如果删除失败,你能直接看到是路径错误、权限不足还是文件被占用等问题。
3. 额外排查点
- 验证路径正确性:在WSL终端执行
ls /mnt/c/Users/mypath/Desktop/cppRoulette/,确认目标文件存在 - 检查权限:如果WSL用户没有该文件的写入权限,可通过
chmod命令调整,或确保Windows文件夹允许WSL访问 - 确认文件未被占用:如果文件正在被Windows编辑器或其他程序打开,WSL无法执行删除操作
修改后的完整代码
#include <iostream> #include <cstdlib> #include <ctime> #include <filesystem> using namespace std; namespace fs = std::filesystem; int main(){ int minNumber = 1, maxNumber = 6; int possibility, chamberNumber; srand(time(0)); possibility = rand() % (maxNumber - minNumber + 1 ) + minNumber; chamberNumber = rand() % (maxNumber - minNumber + 1 ) + minNumber; cout << "First Number: " << possibility << endl << "Second Number: " << chamberNumber << endl; if (possibility == chamberNumber){ const string target_path = "/mnt/c/Users/mypath/Desktop/cppRoulette/delete.txt"; bool success = fs::remove(target_path); if (success) { cout << "You're Dead " << possibility << endl; } else { cerr << "删除失败:" << fs::last_error().message() << endl; } } return 0; }
编译命令保持不变:
g++ -std=c++17 rulet.cpp -o output
内容的提问来源于stack exchange,提问作者CMSNMZ
相关产品推荐
相关产品推荐

