C++ function that checks for the existence of a file or directory
- 2020-04-02 02:52:19
- OfStack
This article illustrates the C++ function code to check whether a file or directory exists. The specific implementation method is as follows:
#include <Windows.h>
BOOL FileExists(LPCTSTR lpszFileName, BOOL bIsDirCheck)
{
//An attempt was made to get the file properties
DWORD dwAttributes = ::GetFileAttributesA(lpszFileName);
if ( INVALID_FILE_ATTRIBUTES == dwAttributes)
{
return FALSE;
}
//Is a directory
if (dwAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (bIsDirCheck) // Currently detected as well Is a directory
{
return TRUE;
}
else
return FALSE;
}
else //Is the file
{
if (bIsDirCheck)
{
return FALSE;
}
else
return TRUE;
}
}
int main(int argc, char *argv[])
{
BOOL bRetDir, bRetFile;
//Test, a directory
bRetDir = FileExists("C:\11\", TRUE);
//Test, a file
bRetFile = FileExists("C:\11\1.xls", FALSE);
return 0;
}
Hope that the article described in the C++ programming to help you.