How can I tell if a given path is a directory or a file? (C/C++)

后端 未结 7 1410
误落风尘
误落风尘 2020-12-08 13:22

I\'m using C and sometimes I have to handle paths like

  • C:\\Whatever
  • C:\\Whatever\\
  • C:\\Whatever\\Somefile

Is there a way to ch

相关标签:
7条回答
  • 2020-12-08 13:41

    Easier to try FileInfo.isDir() in qt

    0 讨论(0)
  • 2020-12-08 13:45

    In Win32, I usually use PathIsDirectory and its sister functions. This works in Windows 98, which GetFileAttributes does not (according to the MSDN documentation.)

    0 讨论(0)
  • 2020-12-08 13:45

    On Windows you can use GetFileAttributes on an open handle.

    0 讨论(0)
  • 2020-12-08 13:56

    With C++14/C++17 you can use the platform independent is_directory() and is_regular_file() from the filesystem library.

    #include <filesystem> // C++17
    #include <iostream>
    namespace fs = std::filesystem;
    
    int main()
    {
        const std::string pathString = "/my/path";
        const fs::path path(pathString); // Constructing the path from a string is possible.
        std::error_code ec; // For using the non-throwing overloads of functions below.
        if (fs::is_directory(path, ec))
        { 
            // Process a directory.
        }
        if (ec) // Optional handling of possible errors.
        {
            std::cerr << "Error in is_directory: " << ec.message();
        }
        if (fs::is_regular_file(path, ec))
        {
            // Process a regular file.
        }
        if (ec) // Optional handling of possible errors. Usage of the same ec object works since fs functions are calling ec.clear() if no errors occur.
        {
            std::cerr << "Error in is_regular_file: " << ec.message();
        }
    }
    

    In C++14 use std::experimental::filesystem.

    #include <experimental/filesystem> // C++14
    namespace fs = std::experimental::filesystem;
    

    Additional implemented checks are listed in section "File types".

    0 讨论(0)
  • 2020-12-08 13:58

    stat() will tell you this.

    struct stat s;
    if( stat(path,&s) == 0 )
    {
        if( s.st_mode & S_IFDIR )
        {
            //it's a directory
        }
        else if( s.st_mode & S_IFREG )
        {
            //it's a file
        }
        else
        {
            //something else
        }
    }
    else
    {
        //error
    }
    
    0 讨论(0)
  • 2020-12-08 14:02

    Call GetFileAttributes, and check for the FILE_ATTRIBUTE_DIRECTORY attribute.

    0 讨论(0)
提交回复
热议问题