问题
I need a function that simply returns bool if there is an entity at the given path, no matter if file or directory. What function to use either in winapi or stl ?
回答1:
GetFileAttributes() will return information about a file system object which can be queried to determine if it is a file or directory and it will fail with if it does not exist.
For example:
#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:
There is PathFileExists (shlwapi)
Determines whether a path to a file system object such as a file or folder is valid.
(Caveat for UNC shares)
来源:https://stackoverflow.com/questions/13842411/how-to-check-if-given-path-is-pointing-to-existing-file-or-directory