例如file1.txt
,我正在将文件重命名为"newFile.txt"
但是当代码下次运行时。该文件newFile.txt
已经存在,所以新创建的文件名称"file1.txt"
没有重命名为"newFile.txt"
我想要的,如果"newFile.txt"
已经存在的重命名"file1.txt"
应该覆盖"file1.txt"
它是否可能?
这是我的代码
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
char data[100];
fstream outfile;
outfile.open("afile.dat" , ios::out );
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
cout << "Reading from the file" << endl;
outfile >> data;
cout << data << endl;
outfile >> data;
cout << data << endl;
outfile.close();
// this is how i am renaming
std::rename("afile.dat" , "file2.txt");
return 0;
}
您的代码只对文件重命名一次。
第二次运行程序时,banana.txt
该目录中已存在文件,并且函数std::rename("afile.dat" , "banana.txt");
返回错误代码。
因此,您需要检查具有新文件名的文件是否已存在或在 function 之后处理错误std::rename
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句