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

标签 c++ windows ifstream

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

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

相关文章:

c++ - 按引用传递然后复制和按值传递在功能上是否不同?

c++ - 在 C++ lldb 中使用重载运算符评估表达式

c - 在 C (Windows) 中使用 USB

c++ - 跳过从数据文件 C++ 中读取字符

c++ - http 中的范围下载

C++类成员回调

.net - 如何从客户端桌面应用程序记录和检索错误消息?

java - 在 Windows 启动时运行 Java 应用程序

C++ 将文本文件创建/解析为函数

c++ - 通过扫描关键字读取文本文件