#include <string>
#include <iostream>
#include <fstream>
using namespace std;
string getUniqueFileName(const std::string& fileName, const std::string& outputDirectory) {
string baseName, extension;
size_t dotIndex = fileName.rfind('.');
if (dotIndex != string::npos) {
baseName = fileName.substr(0, dotIndex);
extension = fileName.substr(dotIndex);
}
else {
baseName = fileName;
}
string newFileName = fileName;
int counter = 1;
while (ifstream(outputDirectory + newFileName).good()) {
newFileName = baseName + "_" + to_string(counter) + extension;
counter++;
}
return newFileName;
}
int main() {
string fileName = "gray_image.txt";
string outputDirectory = "../output_data/";
string outputFileName = getUniqueFileName(fileName, outputDirectory);
cout << "文件名是:" << outputFileName << endl;
ofstream file(outputDirectory + outputFileName);
if (file.is_open()) {
file << "This is a sample text." << endl;
file << "You can write multiple lines in the file." << endl;
file.close();
cout << "File created successfully." << endl;
}
else {
cout << "Failed to create file." << endl;
}
system("pause");
return 0;
}
上述代码实现了一个函数
getUniqueFileName
,该函数接受原始文件名和输出目录作为参数,并根据给定的文件名规则生成一个唯一的文件名。以下是对代码中各段注释的解释:
dotIndex
:查找文件名中最后一个点的位置(扩展名的起始位置)if (dotIndex != std::string::npos)
:如果找到了点
baseName = fileName.substr(0, dotIndex)
:提取文件名的基础部分(点之前的部分)extension = fileName.substr(dotI1ndex)
:提取文件名的扩展部分(点及之后的部分)else
:如果没有找到点,则整个文件名都是基础部分
baseName = fileName
while (std::ifstream(outputDirectory + "/" + newFileName).good())
:检查输出目录中是否已经存在同名的文件
newFileName = baseName + "_" + std::to_string(counter) + extension
:根据计数器生成新的文件名counter++
:递增计数器,以便生成唯一的文件名return newFileName
:返回唯一的文件名在
main
函数中,示例代码调用了getUniqueFileName
函数,并传递了原始文件名和输出目录作为参数。然后,打印出生成的唯一文件名。