Windows C++ / Checking Specific Folder Name by 一半人生

Created the Friday 19 May 2023. Updated 6 months, 1 week ago.

Description:

This C++ code provides three different functions to check whether a given directory exists in a Windows file system. The functions IsDirectory, IsDirectory1, and IsDirectory2 each use different methods to verify the existence of the directory. IsDirectory uses the CRT _access function, IsDirectory1 uses the WinAPI CreateFileA function with the OPEN_EXISTING flag and FILE_FLAG_BACKUP_SEMANTICS attribute to check if a directory handle can be created, and IsDirectory2 uses the CreateDirectoryA function to attempt to create the directory and then checks for an ERROR_ALREADY_EXISTS error. The main function then tests these three methods on a directory named "C:\Cuckoo" and outputs whether each method successfully detected the directory.

Code

            #include <Windows.h>
#include <iostream>
#include <io.h>

// win api
const bool IsDirectory2(std::string& strDirName) {
	const auto iCode = CreateDirectoryA(strDirName.c_str(), NULL);
	if (ERROR_ALREADY_EXISTS == GetLastError())
		return true;
	if (iCode)
		RemoveDirectoryA(strDirName.c_str());
	return false;
}

// win api
const bool IsDirectory1(std::string& strDirName) {
	const HANDLE hFile = CreateFileA(
		strDirName.c_str(),
		GENERIC_READ,                   
		0,                              
		NULL,
		OPEN_EXISTING,                  
		FILE_FLAG_BACKUP_SEMANTICS,     
		NULL);
	if (!hFile || (INVALID_HANDLE_VALUE == hFile))
		return false;
	if(hFile)
		CloseHandle(hFile);
	return true;
}

// crt
const bool IsDirectory(std::string& strDirName) {
	if (0 == _access(strDirName.c_str(), 0))
		return true;
	return false;
}

int main()
{
	std::string strDirName = "C:\\Cuckoo";
	if (IsDirectory(strDirName)) {
		std::cout << "Ture: " << strDirName.c_str() << std::endl;
	}
	else {
		std::cout << "Flase: " << strDirName.c_str() << std::endl;
	}

	if (IsDirectory1(strDirName)) {
		std::cout << "Ture: " << strDirName.c_str() << std::endl;
	}
	else {
		std::cout << "Flase: " << strDirName.c_str() << std::endl;
	}

	if (IsDirectory2(strDirName)) {
		std::cout << "Ture: " << strDirName.c_str() << std::endl;
	}
	else {
		std::cout << "Flase: " << strDirName.c_str() << std::endl;
	}


	return 0;
}