【问题标题】:how to check if given path is pointing to existing file OR directory?如何检查给定路径是否指向现有文件或目录?
【发布时间】:2012-11-30 07:31:44
【问题描述】:

我需要一个函数,如果在给定路径上存在实体,则无论是文件还是目录,它都只返回 bool。在 winapi 或 stl 中使用什么函数?

【问题讨论】:

    标签: c++ file winapi path directory


    【解决方案1】:

    GetFileAttributes() 将返回有关文件系统对象的信息,可以查询该对象以确定它是文件还是目录,如果不存在则会失败。

    例如:

    #include <windows.h>
    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        if (2 == argc)
        {
            const DWORD attributes = GetFileAttributes(argv[1]);
            if (INVALID_FILE_ATTRIBUTES != attributes)
            {
                std::cout << argv[1] << " exists.\n";
            }
            else if (ERROR_FILE_NOT_FOUND == GetLastError())
            {
                std::cerr << argv[1] << " does not exist\n";
            }
            else
            {
                std::cerr << "Failed to query "
                          << argv[1] 
                          << " : "
                          << GetLastError()
                          << "\n";
            }
    
        }
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      PathFileExists(shlwapi)

      确定文件系统对象(如文件或 文件夹有效。

      (对 UNC 股票的警告)

      【讨论】:

      • 此外,260 个字符的路径名长度限制不仅仅是理论上的限制。可以在this Q&A 中找到限制较少的替代方案。
      猜你喜欢
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 2011-08-22
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多