c++创建文件时重命名同名文件

在保存文件时,会出现和保存文件名同名的文件,一般情况下会在新建的文件后面加上序号后,如test(1).dat, test(2).dat

下面用一种比较笨的方法来实现:

 1 // #include <sys/io.h>
 2 #include <dirent.h>
 3 #include <string.h>
 4 #include <unistd.h>
 5 
 6 #include <fstream>
 7 #include <iostream>
 8 #include <string>
 9 
10 #include "log/log.h"
11 
12 std::string filename;
13 
14 void findName(std::string path) {
15     DIR* dp;
16     struct dirent* dirp;
17     if ((dp = opendir(path.c_str())) == nullptr) {
18         LOG_ERROR("open dir[{}] failed!", path);
19         return;
20     }
21     int cnt = 0;  //用于计数有多少个重名文件
22 
23     while ((dirp = readdir(dp)) != nullptr) {
24         if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
25             continue;
26         std::string d_name = dirp->d_name;
27         if (d_name.find(".mp4") != std::string::npos) {
28             std::string subStr = filename.substr(0, filename.length() - 4);  //取出除去后缀的子串
29             if (d_name.find(subStr) != std::string::npos) {
30                 cnt++;   //每找到一个重名文件就加一
31             }
32         }
33     }
34     if (cnt != 0) {
35         std::string subStr = filename.substr(0, filename.length() - 4);
36         filename = fmt::format("{}({}).mp4", subStr, cnt);
37         LOG_INFO("filename={}", filename);
38     }
39 }
40 
41 int main() {
42     std::ofstream file;
43     while (std::cin >> filename) {
44         findName("./");
45 
46         file.open(filename, std::ios::binary);
47         if (!file.is_open()) {
48             LOG_ERROR("open failed");
49         }
50         file.close();
51     }
52 
53     return 0;
54 }

每次使用readdir后,readdir会读到下一个文件,readdir是依次读出目录中的所有文件,每次只能读一个

原文地址:https://www.cnblogs.com/y4247464/p/14692968.html