gpt4 book ai didi

c++ - 如果在 C++ 中不工作,请检查绝对文件路径

转载 作者:太空宇宙 更新时间:2023-11-04 13:14:10 25 4
gpt4 key购买 nike

我知道有类似的问题,但没有解决我的问题。

我使用了 std::ifstream 和 PathFileExist 但它总是返回 false 并且我的错误处理程序 GetLastError() 总是给出消息

"The system cannot find the file specified"

我使用的是 Visual Studio 2012,我已经使用绝对路径测试了不同目录中的文件,以消除“权限”和“错误路径”问题的可能性。

这是我的代码片段。

注意:ErrorExit 只是一个包装器,它使用 GetLastError() 来显示错误消息。

尝试A

if (std::ifstream((LPCWSTR)"C:\\Windows\\write.exe"))
{
// do some thing if file is found
}
else
ErrorExit(TEXT("ifstream"));

或尝试B

std::ifstream f;
f.open(L"C:\\Windows\\write.exe", ios::in);

if (f.is_open())
{
// do something if file is open
}

或者首先检查权限尝试C

if (_waccess(L"C:\\Windows\\write.exe", 04) == 0)

if (std::ifstream((LPCWSTR)"C:\\Windows\\write.exe"))
{
// do some thing if file is found
}
else
ErrorExit(TEXT("ifstream"));
}
else
ErrorExit("_waccess");

我已经尝试过不同的字符串约定:

L"C:\\Windows\\write.exe"
(LPCWSTR)"C:\\Windows\\write.exe"
_T("C:\\Windows\\write.exe")
TEXT("C:\\Windows\\write.exe")

仍然没有运气。

提前致谢。

最佳答案

我看到您有特定于 Windows 的代码(使用 LPCWSTR 等)

所以使用Win API

#include <windows.h>
...
if (GetFileAttributesW(L"C:\\windows\\write.exe") == -1)
file_not_found(); // file does not exist
else
file_exists(); // do some thing if file is found

关于c++ - 如果在 C++ 中不工作,请检查绝对文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38242131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com