C++ 批量修改文件名
生活随笔
收集整理的這篇文章主要介紹了
C++ 批量修改文件名
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++ 批量修改文件名
前言
在網上下一些學習資料,可是每個文件后帶有一些其他無關的文字,形式如,某某某【某某某】.mp4,其中【】及其內容皆為無關內容,本文代碼程序用于批量刪除每個MP4文件后的【某某某】。
注意
文件名即為中文字符,不同于英文格式,所以以下代碼中在需要的時候都使用了寬字符處理。
代碼
#include <iostream> #include <string> #include <vector> #include <io.h> int main() {//使用寬字節流對象,綁定為中文locale china("chs");//use china characterwcin.imbue(china);//use locale objectwcout.imbue(china);wstring dirpath = L"E:\\test\\"; //注意寬字符或寬字符串在初始化時要加前綴L_wfinddata_t file; //使用寬字節的_wfinddata_t對象而非_finddata_tlong lf; //是否遍歷完畢的標志位wchar_t suffixs[] = L"*.mp4"; //要尋找的文件類型后綴,也統一使用寬字符串vector<wstring> fileNameList; //文件夾下該類型文件的名字向量表wchar_t* p;int psize = dirpath.size() + 6; //后面要把后綴加上,為了防止數組越界需要多開一點空間,6個正好p = new wchar_t[psize];wcscpy(p, dirpath.c_str());//獲取文件名,存入向量表if ((lf = _wfindfirst(wcscat(p, suffixs), &file)) == -1l){cout << "文件沒有找到!\n";} else{cout << "\n文件列表:\n";do {//wcout << file.name << endl;wstring str(file.name);fileNameList.push_back(str);wcout << str << endl;} while (_wfindnext(lf, &file) == 0);}_findclose(lf); //使用完畢后要關閉文件delete[] p;//遍歷文件名向量表,并進行修改cout << "\n開始修改文件名:" << endl;for (vector<wstring>::iterator iter = fileNameList.begin(); iter != fileNameList.end(); ++iter){wstring oldName = dirpath + *iter; //記得加上絕對路徑auto pos = iter->find(L"【");wstring newName = dirpath + iter->substr(0, pos);newName += L".mp4";wcout << "oldName:" << oldName << endl;wcout << "newName:" << newName << endl;wcout << "oldName size = " << oldName.size() << endl;wcout << "newName size = " << newName.size() << endl;int ret = _wrename(oldName.c_str(), newName.c_str());if (ret != 0)perror("rename error!");cout << endl;}system("pause");return 0; }讀者可以根據自身需求修改代碼。
溫馨提示
最好在使用程序前備用原資料,避免出現意外情況(比如我,在編寫使用過程中忘記添加決定路徑,導致原資料改名后跑到了項目路徑下😑)。
參考
https://blog.csdn.net/Dr_Myst/article/details/81463450
總結
以上是生活随笔為你收集整理的C++ 批量修改文件名的全部內容,希望文章能夠幫你解決所遇到的問題。