小智 105
stat()会告诉你这个.
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
}
Run Code Online (Sandbox Code Playgroud)
Col*_*len 28
调用GetFileAttributes,并检查FILE_ATTRIBUTE_DIRECTORY属性.
jef*_*ffm 13
在Win32中,我通常使用PathIsDirectory及其姐妹函数.这适用于Windows 98,GetFileAttributes没有(根据MSDN文档.)
随着C++ 14/C++ 17可以使用独立于平台is_directory(),并is_regular_file()从文件系统库.
#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();
}
}
Run Code Online (Sandbox Code Playgroud)
在C++ 14中使用std::experimental::filesystem.
#include <experimental/filesystem> // C++14
namespace fs = std::experimental::filesystem;
Run Code Online (Sandbox Code Playgroud)
"文件类型"部分列出了其他实现的检查.