Nov 202010

This function will create an entire path to a folder if any part of the path doesn’t already exist. It is useful for ensuring that a path exists before trying to open a new file in a subfolder. This uses some of the file functions I posted last month.

//
//	Create all folders needed to get to a path if they are not already there.
//
void CreateAllDirectories(CString strDir)
{
	if(strDir.IsEmpty())
		return;
        // remove ending / if exists
	RemoveSlash(strDir);

	 // base case . . .if directory exists
	if(FileExists(strDir)) 
		return;

 // recursive call, one fewer directories
 int nFound = strDir.ReverseFind(_T('\\'));
 CreateAllDirectories(strDir.Left(nFound)); 

 // actual work
 CreateDirectory(strDir,NULL); 
}

Leave a Reply

(required)

(required)