How to check if Directory already Exists in MFC(VC++) ? I am using below code to get current application Path and there i am creating NDSLog folder so that all my Logfiles should place there , now i want to check the condition if NDSLog folder already exists dont create it .How to do that ?
Thanks.
char strPathName[_MAX_PATH];
::GetModuleFileName(NULL, strPathName, _MAX_PATH);
// The following code will allow you to get the path.
CString newPath(strPathName);
int fpos = newPath.ReverseFind('\\');
if (fpos != -1)
newPath = newPath.Left(fpos+1);
newPath += "NDSLog\\" ;
CreateDirectory(newPath,NULL);
The Directory static class in the System.IO namespace provides the Exists() method to check the existence of a directory on the disk. This method takes the path of the directory as a string input, and returns true if the directory exists at the specified path; otherwise, it returns false.
Use ifile. open() is mainly used to check if a file exists in the specific directory or not. In the filing, a stream refers to an abstract that signifies a method where input as well as output processes are executed. “ifile. open()” takes one argument that is the name of the file.
The FileExists Method (System::SysUtils::FileExists) is a SysUtils Method in C++ Builder that checks whether a specified file exists. FileExists returns True if the file specified by FileName exists. If the file does not exist, FileExists returns False.
The simplest way to check if a file/directory exists is to use GetFileAttributes
:
if (GetFileAttributes(newPath) == INVALID_FILE_ATTRIBUTES) {
CreateDirectory(newPath,NULL);
}
Note that the function will return INVALID_FILE_ATTRIBUTES
even if it fails due to some other reason, such as not having permissions to access the file, so you should check the return value of CreateDirectory
to make sure that it succeeded.
Actually, you don't need to check whether the directory already exists; CreateDirectory
will set an error code if the directory already exists:
if (!CreateDirectory(newPath,NULL)) {
if (GetLastError() == ERROR_ALREADY_EXISTS) {
// directory already exists
} else {
// creation failed due to some other reason
}
}
How about PathIsDirectory()
? In the original example, you can use PathRemoveFilespec()
followed by PathCombine()
to add a new filename/extension. In the unlikely case that your target is only Windows 8 or later, there are safer PathCch...()
flavors of these functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With