- MFC给重复的文件重命名
CString CAudioRecorder::MakeUniqueName(const CString& m_strFile)
{
CString strUniquePath = m_strFile;
if (PathFileExists(m_strFile))
{
TCHAR szPathNoExtension[MAX_PATH];
lstrcpy(szPathNoExtension, m_strFile);
PathRemoveExtension(szPathNoExtension);
LPTSTR pszExtension = PathFindExtension(m_strFile);
const CString strFormat = _T("%s_%03d%s");
int i = 1;
CString strTestName;
CString strFixedTestName;
int nAppendCharsLength = 0;
do
{
// Try generating the formatted string
strTestName.Format(strFormat, szPathNoExtension, i, pszExtension);
// Appending characters to the string may make it longer than our buffer. In this case we need to remove
// some characters from the end of the original filename.
if (strTestName.GetLength() > (MAX_PATH - 1))
{
// Increase the running total of appended characters by the newly added appended characters
nAppendCharsLength += strTestName.GetLength() - m_strFile.GetLength();
// The length of the trimmed original string will be the original filepath length minus the appended
// characters and the extension
int nTrimFilenameLength = m_strFile.GetLength() - (nAppendCharsLength + lstrlen(pszExtension));
// Trim the original filename
if (nTrimFilenameLength >= 0)
{
szPathNoExtension[nTrimFilenameLength] = NULL;
}
// Re-generate the formatted string
strFixedTestName.Format(strFormat, szPathNoExtension, i, pszExtension);
}
else
{
// If no additional characters have been appended, we can use the formatted string we already generated
strFixedTestName = strTestName;
}
i++;
} while (PathFileExists(strFixedTestName));
strUniquePath = strFixedTestName;
}
return strUniquePath;
}
网友评论