【问题标题】:how to delete data saved in a text file in c++如何在C++中删除保存在文本文件中的数据
【发布时间】:2013-04-26 12:51:10
【问题描述】:

我一直试图想出一个代码来删除保存在文本文件中的数据,但无济于事。应该怎么做??在 c++ 中,这是我的代码,我该如何改进它,以便删除保存的数据可能是逐个条目?

  #include<iostream>
  #include<string>
  #include<fstream>
  #include<limits>
  #include<conio.h>
   using namespace std;

  int main()

  {
  ofstream wysla;
  wysla.open("wysla.txt", ios::app);
 int kaput;

 string s1,s2;
 cout<<"Please select from the List below"<<endl;
 cout<<"1.New entry"<<endl;
  cout<<"2.View Previous Entries"<<endl;
  cout<<"3.Delete an entry"<<endl;
  cin>>kaput;
  switch (kaput)
 {

 case 1:

    cout<<"Dear diary,"<<endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
    getline(cin,s1);
    wysla<<s1;
   wysla.close();

   break;
   }
  return 0;
   }

【问题讨论】:

  • 数据?你的意思是文本文件中的任意行?你不能到位
  • 只有一种方法可以从文件中间删除。将整个文件读入内存,删除内存中不需要的部分。从内存中写出整个文件。
  • @brad 不,这不是一个私人项目
  • @john 不,这不是唯一的方法,但它肯定是最简单的方法。
  • @john 这不是我通常这样做的方式,事实上,这不是一个很好的方式。通常的方法是将文件复制到临时文件中,在复制时即时进行更改。然后关闭临时文件,只有在关闭后输出流是好的,删除原来的,重命名临时文件。

标签: c++


【解决方案1】:

我可以为您提供我用于相同目的的最快方法。使用函数http://www.cplusplus.com/reference/cstdio/fseek 去准确的位置。假设您将 name 保存在文件中。那么名单就是

Alex
Timo
Vina

删除Alex时,插入一个额外的字符前缀,以便将其标记为已删除

-Alex
Timo
Vina

必要时不会显示。

如果您不想这样做,则必须在没有该特定行的情况下进行复制。请参阅Replace a line in text file 的帮助。在你的情况下,你用空字符串替换。

【讨论】:

  • 你建议如何插入多余的字符?
【解决方案2】:

在矢量的帮助下完成。

//Load file to a vector:
string line;
vector<string> mytext;
ifstream infile("wysla.txt");
if (infile.is_open())
{
    while ( infile.good() )
    {
        getline (infile,line);
        mytext.push_back(line);
    }
    infile.close();
}
else exit(-1);

//Manipulate the vector. E.g. erase the 6th element:
mytext.erase(mytext.begin()+5); 

//Save the vector to the file again:
ofstream myfile;
myfile.open ("wysla.txt");
for (int i=0;i<mytext.size();i++)
    myfile << mytext[i];
myfile.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多