批量重命名程序

批量重命名

1. 前置知识

1.1. _finddata_t 类(结构体)

#include<io.h>            // finddata的头文件
struct _finddata_t {
  unsigned attrib;        // 文件属性的储存位置
  time_t time_create;     // 存储文件创建时间
  time_t time_access;     // 文件最后一次被访问的时间。
  time_t time_write;      // 文件最后一次被修改的时间。
  _fsize_t size;          // 大小
  char name[_MAX_FNAME];  // 文件名
};

这是_finddata_t类的组成

1.2.1 常用函数

long _findfirst(char *filespec, _finddata_t *fileinfo );

该函数是是在一个文件夹内查找文件,支持通配符
filespec 包含文件地址的字符串
fileinfo :这里就是用来存放文件信息的结构体的指针。(这个结构体必须在调用此函数前声明,不过不用初始化),函数会把搜索到的信息放进该变量.
函数返回值是一个long类型的句柄,若查找失败则返回-1

int _findnext( long handle, struct _finddata_t *fileinfo );

返回值: 若成功返回0,否则返回-1。
handle:即由_findfirst函数返回回来的句柄。
fileinfo:文件信息结构体的指针。
该函数的主要作用就是查找下一个文件

int _findclose( long handle );

返回值: 成功返回0,失败返回-1。
关闭句柄

1.2. stringstream类

https://blog.csdn.net/qq_43085783/article/details/120961614

2. 程序源码

#include <io.h>

#include <cstring>
#include <iostream>
#include <sstream>
using namespace std;

string path, pre, p;
int cnt = 1;
long hfile = 0;
struct _finddata_t fileinfo;

void getdata();
string new_filename();
string getname();

int main() {
  getdata();

  hfile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo);
  if (hfile != -1) {
    do {
      if (strcmp(fileinfo.name, ".") == 0 || strcmp(fileinfo.name, "..") == 0)
        continue;
      p = "";
      cout << cnt << ":" << fileinfo.name << endl;
      string newName = new_filename();
      rename(p.assign(path).append("\\").append(fileinfo.name).c_str(),
             newName.c_str());
    } while (!_findnext(hfile, &fileinfo));
    _findclose(hfile);
    cout << "success!" << endl;
  }
  system("pause");
  return 0;
}

void getdata() {
  cout << "1:";
  getline(cin, path);
  cout << "2:";
  cin >> pre;
  cout << endl;
}

string new_filename() {
  string filename = getname();
  stringstream ss;
  ss << pre << (int)cnt;
  cnt++;
  string type =
      filename.substr(filename.find('.'), filename.size() - filename.find('.'));
  ss << type;
  string new_name;
  ss >> new_name;
  return p.assign(path).append("\\").append(new_name);
}

string getname() {
  string s = "";
  int len = strlen(fileinfo.name);
  for (int i = 0; i < len; i++) {
    s.push_back(fileinfo.name[i]);
  }
  return s;
}
上一篇:effective python


下一篇:《高性能MySQL》读书笔记