【发布时间】:2020-07-20 02:10:00
【问题描述】:
我想要一个由用户提供的名称创建的文件。如果文件名已经存在,我希望在创建之前自动修改文件名。
if (GetFileAttributesA((name).c_str()) != INVALID_FILE_ATTRIBUTES)
{
int num = 0;
//If True: Modify File Name
while (GetFileAttributesA((name + "" + to_string(num) + "").c_str()) != INVALID_FILE_ATTRIBUTES)
{
cout << (GetFileAttributesA((name + "" + to_string(num) + "").c_str()) != INVALID_FILE_ATTRIBUTES) << endl;
num++;
}
CreateFileA((name + "" + to_string(num) + "" + ".txt").c_str(), NULL, NULL, NULL, 2, NULL, NULL);
cout << "Created new file at: ";
cout << (name + "" + to_string(num) + "" + ".txt").c_str() << endl;
}
else
{
CreateFileA(name.c_str(), NULL, NULL, NULL, 2, NULL, NULL);
cout << "Created new file at: ";
cout << (name + ".txt").c_str() << endl;
}
第一次运行程序
Created new file at: Created new file at: D:\Users\Me\HD-Visual Studio Repos\Visual Studio Repo\McFG\Text Generator Function Generator\Generated txt\base.txt
第二次运行程序
Created new file at: Created new file at: D:\Users\Me\HD-Visual Studio Repos\Visual Studio Repo\McFG\Text Generator Function Generator\Generated txt\base1.txt
第三次运行程序
Created new file at: Created new file at: D:\Users\Me\HD-Visual Studio Repos\Visual Studio Repo\McFG\Text Generator Function Generator\Generated txt\base1.txt
到第三次时,它会再次开始创建副本。
name = D:\Users\Me\HD-Visual Studio Repos\Visual Studio Repo\McFG\Text Generator Function Generator\Generated txt\base
【问题讨论】:
-
您正在检查的文件,
GetFileAttributes与您正在创建的文件不同。注意你在哪里输入num -
典型的问题是代码变得复杂而无用,计算多次相同的事情(实际上几乎由于错误而导致相同的事情)...
-
@JaedonKLB 我们都明白这一点,但是你你明白他的话吗?
-
@JaedonKLB 根本不使用
GetFileAttributes,这会引入竞争条件。如果文件存在,CreateFile有失败的标志。循环调用CreateFile,每次迭代创建一个新的文件名,直到创建成功 -
@bruno 如果循环正确处理错误,则不会。
GetLastError会告诉他为什么CreateFile会失败。在这种情况下,循环 whileCreateFile仅以ERROR_FILE_EXISTS失败,其他任何情况都是致命错误,应该会中断循环