* 我想把第一个文件("c constituencies")的内容转移到第二个文件("temp"),然后删除原来的("c constituencies")文件,然后重命名()("temp")到("c constituencies"),这样就可以用一个特定的入口线来刷新。在新生成的文件("temp")中先找到它,然后不添加它,然后删除旧的("选区")文件,并将("temp")重命名为新的("选区"),但在这个过程中,我的两个文件都被删除了。请帮助*
void updateOrDelete()
{
fstream constituencies("constituencies.txt", ios::out | ios::in);
fstream temp("temp.txt", ios::out | ios::in);
string deleteline;
string line;
cout << "Which constituency do you want to remove? \n";
cin >> deleteline;
while (getline(constituencies, line))
{
if (line != deleteline)
{
temp << line << endl;
}
}
constituencies.close();
temp.close();
remove("constituencies.txt");
rename("temp.txt", "constituencies.txt");
}
这一行 失败 如果 temp.txt
不存在。
fstream temp("temp.txt", ios::out | ios::in);
但你没有注意到,因为你没有检查它是否成功。
补救措施。
ifstream constituencies("constituencies.txt");
if(constituencies) {
// constituencies.txt successfully opened for reading
ofstream temp("temp.txt");
if(temp) {
// temp.txt successfully opened for writing
} else {
// fail
}
} else {
// fail
}
这是一个完整版的函数,增加了一些错误检查,并且把用户交互移出了,所以你必须要用 deleteline
你想从文件中删除。
// returns true if successful and false otherwise
bool updateOrDelete(const std::string& deleteline) {
static const char* orig = "constituencies.txt";
static const char* temp1 = "temp1.txt";
static const char* temp2 = "temp2.txt";
// make sure you are the only one processing the file
if(std::rename(orig, temp1) == 0) {
// open for reading and check if it succeeded
if(std::ifstream in(temp1); in) {
// open for writing and check if it succeeded
if(std::ofstream out(temp2); out) {
std::string line;
// do your processing
while(std::getline(in, line)) {
if(line != deleteline) {
out << line << '\n';
}
}
// check if the new file is still in a good state before closing it
bool success = static_cast<bool>(out);
out.close();
in.close();
if(success) {
// all's well - move the processed file into place
// and remove the old (renamed) original
return std::rename(temp2, orig) == 0 && std::remove(temp1) == 0;
}
// processing failed
// remove the corrupt/truncated file
std::remove(temp2);
}
}
// try to restore the original file
std::rename(temp1, orig);
}
// if we get here, something failed
return false;
}