給一個目錄下的一個已存在的檔案生成一個新的檔名
阿新 • • 發佈:2019-01-27
微軟在Shlobj.h中提供了PathYetAnotherMakeUniqueName,可以直接使用。
下邊是我自己編寫的程式碼:
c:\1\1(aa).txt
c:\1\1(aa).txt不存在 -> c:\1\1(aa).txt
c:\1\1(aa).txt已存在,c:\1\1(aa) (0).txt不存在 -> c:\1\1(aa) (0).txt
c:\1\1(aa).txt已存在,c:\1\1(aa) (0).txt已存在 -> c:\1\1(aa) (1).txt
VOID ModifySaveAs(LPTSTR lpPath) { LPTSTR lpPostion = NULL; LPTSTR lpPositionPre = NULL; TCHAR NewFileName[MAX_PATH] = {0}; LPTSTR lpPositionPost = NULL; ULONG ulCount = 0; TCHAR Num[MAX_PATH] = {0}; TCHAR TmpFileName[MAX_PATH] = {0}; do { if (!lpPath) break; // 確保儲存目錄存在 lpPostion = StrRChr(lpPath, lpPath + _tcslen(lpPath), _T('\\')); if (!lpPostion) break; CopyMemory(NewFileName, lpPath, (lpPostion - lpPath) * sizeof(TCHAR)); if (!PathFileExists(NewFileName)) { SHCreateDirectory(NULL, NewFileName); break; } _tcscpy_s(TmpFileName, _countof(TmpFileName), lpPath); while (PathFileExists(TmpFileName)) { ulCount = 0; lpPostion = NULL; lpPositionPost = NULL; lpPositionPre = NULL; ZeroMemory(Num, sizeof(Num)); ZeroMemory(NewFileName, sizeof(NewFileName)); lpPostion = StrRChr(TmpFileName, TmpFileName + _tcslen(TmpFileName), _T('.')); if (lpPostion) lpPostion--; else lpPostion = TmpFileName + _tcslen(TmpFileName) - 1; lpPositionPost = StrRChr(TmpFileName, lpPostion + 1, _T(')')); lpPositionPre = StrRChr(TmpFileName, lpPostion + 1, _T('(')); if (lpPositionPre && lpPositionPost && lpPositionPre < lpPositionPost) { lpPositionPost--; lpPositionPre++; CopyMemory(NewFileName, TmpFileName, (lpPositionPre - TmpFileName) * sizeof(TCHAR)); CopyMemory(Num, lpPositionPre, (lpPositionPost - lpPositionPre + 1) * sizeof(TCHAR)); ulCount = StrToInt(Num); if (ulCount || ((_tcslen(Num) == 1) && ((*Num >= _T('0')) && (*Num <= _T('9'))))) { ulCount++; StringCbPrintf(Num, sizeof(Num), _T("%d"), ulCount); _tcscat_s(NewFileName, Num); _tcscat_s(NewFileName, lpPositionPost + 1); ZeroMemory(TmpFileName, MAX_PATH * sizeof(TCHAR)); _tcscpy_s(TmpFileName, MAX_PATH, NewFileName); } else { CopyMemory(NewFileName + (lpPositionPre - TmpFileName), lpPositionPre, (lpPositionPost - lpPositionPre + 2) * sizeof(TCHAR)); _tcscat_s(NewFileName, _T(" (")); StringCbPrintf(Num, sizeof(Num), _T("0")); _tcscat_s(NewFileName, Num); _tcscat_s(NewFileName, _T(")")); _tcscat_s(NewFileName, lpPostion + 1); ZeroMemory(TmpFileName, MAX_PATH * sizeof(TCHAR)); _tcscpy_s(TmpFileName, MAX_PATH, NewFileName); } } else { CopyMemory(NewFileName, TmpFileName, (lpPostion - TmpFileName + 1) * sizeof(TCHAR)); _tcscat_s(NewFileName, _T(" (")); StringCbPrintf(Num, sizeof(Num), _T("0")); _tcscat_s(NewFileName, Num); _tcscat_s(NewFileName, _T(")")); _tcscat_s(NewFileName, lpPostion + 1); ZeroMemory(TmpFileName, MAX_PATH * sizeof(TCHAR)); _tcscpy_s(TmpFileName, MAX_PATH, NewFileName); } } CopyMemory(lpPath, TmpFileName, _tcslen(TmpFileName) * sizeof(TCHAR)); *(lpPath + _tcslen(TmpFileName)) = _T('\0'); } while (FALSE); return; }