我知道也有类似的问题,但这并不能解决我的问题。

我使用了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/

10-12 02:38
查看更多