如何删除.txt文件上的记录, 例如,我在.txt文件上有记录:
Juan John Josh
Harry Potter Harry
Razor Paper Stone
用户将输入要删除的名称, 示例:用户输入名称,Harry,然后录音机将更新并删除记录Harry Potter Harry。
我要求输入密码。 请回复。
答案 0 :(得分:0)
这取决于文件格式:
如果所有记录(=行)具有相同的长度(例如:使用空格填充),则可以获取最后一条记录并写入要删除的记录,并修剪文件以排除最后一条记录。
如果是纯文本文件,则必须复制数据,直到文件结尾,如下所示:
答案 1 :(得分:0)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** arg)
{
//declare testing this is the original text file variable
ifstream testing;
//open test.txt this is the original text file
testing.open("test.txt");
//decalare a temporary text file variable
ofstream temp;
//open a temporary text file
temp.open("temp.txt");
// user input to delete record
cout<<"Enter Name to delete: ";
//declaration of variables
//variable for the input of the user
string name;
//variable for the record inside the original text file
string name1;
//reading input as the value of the variable name.
cin>>name;
//while this is for reading the original text file and the record will be the value for the variable name1
while(testing>>name1)
{
//if variable name2(record) not equal to variable name(input)
if(name2 != name)
{
//all the records in the original text file except to the record that the user inputted will be copied to the temporary text file which is temp.txt.
temp<<name1<<" "<<name2<<" "<<name3<<" "<<grade1<<" "<<grade2<<" "<<grade3<<endl;
}
}
//closing temp.txt
testing.close();
//closing original text file which is test.txt
temp.close();
//removing the original text file because it contains all the records including the record that was intended to be deleted.
remove("test.txt");
//renaming the temporary text file(temp.txt) to become the original text file(test.txt)
//note: that the temporary text file contains all the records except to the record the user deleted.
//and now renamed to be the original text file.
rename("temp.txt", "test.txt");
//the record is now deleted and its done hahaha
return 0;
}