Get path with unique file name in Windows (C++/MFC)

Sometimes, when a file with same name already exists, we wish to generate a new unique file name. The following function does this. Coded in C++/MFC. A number is suffixed to the file name. You can specify your own number format.

//generates a file name that is unique so that
//we don't have to replace an existing file in the same path
//so if "New Document.txt" exists
//we will generate "New Document - 1.txt"
//we will keep check if the file exists
//and when the file does not exist we will exit
//strAppendedNumberFormat must contain %d
BOOL GetPathWithUniqueFileName(CString & strFilePath, CString strAppendedNumberFormat)
	int iMaxRetries = 1000;
	int iCtr;
	CString strNewFilePath;
	CString strAppendedText;
	CString strExtension;
	//if this file does not exist, then just return
	//it means that we can create file with this name
	if (!PathFileExists(strFilePath)) return TRUE;
	iCtr = 0;
	while(iCtr < iMaxRetries)
		strNewFilePath = strFilePath;
		//will get .txt for example - it includes the period (.)
		strExtension = PathFindExtension(strNewFilePath);
		strAppendedText.Format(strAppendedNumberFormat, iCtr);
		strNewFilePath += strAppendedText;
		strNewFilePath += strExtension;
		if (!PathFileExists(strFilePath)) break;
	return TRUE;

Leave a Reply

Your email address will not be published. Required fields are marked *