根据对应规则,批量修改文件名
如果用cmake方式编译,需要自己写一个cmakelist文件
#include <algorithm>
#include <dirent.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <vector>
using namespace std;
string path_name = "/home/gitrepo/rename_files/rz/";
vector<string> macs;
vector<string> names;
vector<string> getFiles(string cate_dir) {
vector<string> files; //存放文件名
DIR *dir;
struct dirent *ptr;
char base[1000];
if ((dir = opendir(cate_dir.c_str())) == NULL) {
perror("Open dir error...");
exit(1);
}
while ((ptr = readdir(dir)) != NULL) {
if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
continue;
if (ptr->d_type == 8) /// file
files.push_back(ptr->d_name);
if (ptr->d_type == 10) /// link file
files.push_back(ptr->d_name);
string folder_name = ptr->d_name;
// 去掉文件名的头尾,只保留中间mac,用于匹配
folder_name.erase(0, 4);
folder_name.erase(12);
// cout<<folder_name<<endl;
/* enum {
DT_UNKNOWN = 0, //未知类型
#define DT_UNKNOWN DT_UNKNOWN
DT_FIFO = 1, //管道
#define DT_FIFO DT_FIFO
DT_CHR = 2, //字符设备
#define DT_CHR DT_CHR
DT_DIR = 4, //目录
#define DT_DIR DT_DIR
DT_BLK = 6, //块设备
#define DT_BLK DT_BLK
DT_REG = 8, //常规文件
#define DT_REG DT_REG
DT_LNK = 10, //符号链接
#define DT_LNK DT_LNK
DT_SOCK = 12, //套接字
#define DT_SOCK DT_SOCK
DT_WHT = 14 //链接
#define DT_WHT DT_WHT
};
*/
for (int i = 0; i < macs.size(); i++) {
if (folder_name == macs[i]) {
// 重命名文件中需要添加的部分
string add_name = "(###-" + names[i] + ")";
// 旧文件名
string oldName = path_name + ptr->d_name;
// 新文件名
string newName = path_name + add_name + ptr->d_name;
// .c_str()将 string 转换为char *
rename(oldName.c_str(), newName.c_str());
// free(oldNamePointer);
// free(newNamePointer);
cout << "Mac:" << folder_name << " 修改为: " << add_name << endl;
}
}
}
closedir(dir);
//排序,按从小到大排序
// sort(files.begin(), files.end());
return files;
}
int main() {
// 读取mac地址、以及对应的人名
string mac_, name_;
ifstream ifs_mac, ifs_name;
ifs_mac.open("/home/gitrepo/rename_files/data/mac_.txt", ios::in);
ifs_name.open("/home/gitrepo/rename_files/data/name_.txt", ios::in);
if (ifs_mac.is_open() && ifs_name.is_open()) {
while (ifs_mac >> mac_ && ifs_name >> name_) {
macs.push_back(mac_);
names.push_back(name_);
}
}
ifs_mac.close();
ifs_name.close();
cout << "names.size():" << names.size() << endl;
cout << "macs.size():" << macs.size() << endl;
// for(int i=0; i<names.size(); i++){
// cout<<names[i]<< "--"<<macs[i]<<endl;
//}
cout << "----------------------------------------------" << endl;
// 读取文件并按照mac表进行修改
vector<string> files = getFiles(path_name);
cout << "files.size():" << files.size() << endl;
// for (int i = 0; i < files.size(); i++) {
// cout << files[i] << endl;
//}
return 0;
}