gpt4 book ai didi

c++ - 如何不覆盖文件,C++ 日志记录

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:09 26 4
gpt4 key购买 nike

这是我的代码。每次我“保存”时,它都会覆盖旧的 txt 文件。如何将新行或图集输出到同一文件中到新文件。这是一个动态数组,我正在使用开关盒。输入数据后,我想将其保存到文本文件中。并在下次加载它。加载功能也很好用。

#include<iostream>
#include<string>
#include<fstream> //to save file in text
using namespace std;
int main ()
{
int *p1;
int size=0;
int counter=0;
p1 = new int[size];
int userchoice;
int i;
int position;
while(1)
{
cout << "Please enter your choice " << endl;
cout<<endl;
cout << "To insert Press '1'" << endl;
cout << "To Delete press '2'" << endl;
cout << "To View press '3'" << endl;
cout << "To Search press '4'" << endl;
cout << "To Save Press '5'" << endl;
cout << "To Load Previously saved Data press '6'" << endl;
cout << "To Exit press '7'" << endl;
cout << endl;
cin>>userchoice;
switch(userchoice)
{
case 1:
cout<<"Enter a Number -->";
cin>>p1[size];
counter++;
size++;
break;
case 2:
int udelete;
cout<<"Enter a number to delete --> ";
cin>>udelete;
for(position = 0; position<size; position++)
{
if (p1[position] == udelete)
break;
}
if(position>size)
{
cout<<"The number is not in the memory ";
cout<<endl;
break;
}
for(i = position; i<size; i++){
p1[i]=p1[i+1];
}
size--;
cout<<"Successfully Deleted!!! ";
cout<<endl;
break;
case 3:
for (i=0; i<size; i++)
{
cout<<"Your data" <<" " << i << " " << "-->" <<p1[i]<<endl;
}
break;
case 4:
{
int usearch;
cout<<"Please enter the figure you would like to search ";
cout<<"->";
cin>>usearch;
for(i=0; i>size; i++)
{
if (p1[size]==usearch)
break;
}
if(usearch==size)
{
cout<<"not found";
}
cout<<"Position at: "<<i+1<<endl;
break;
}
case 5:
{
ofstream save;
save.open("data.txt");
for (i=0; i<size; i++)
{
save <<p1[i] <<endl;
}
save.close();
cout<<"File Saved "<<endl;
break;
}
case 6:
{
string read;
ifstream file_("data.txt");
if (file_.is_open())
{
while(getline(file_,read))
{
cout << read << "\n";
}
file_.close();
}
else
cout << "File Not open" << endl;
cin.get();
break;
}
case 7:
{
return 0;
}
}
}}

最佳答案

以“附加”模式打开文件。

save.open( "data.txt", ofstream::out | ofstream::app );

如果文件不存在,这将创建文件,否则将写指针定位在文件末尾。

您不必显式调用 open。有一个构造函数可以为您完成:

ofstream save( "data.txt", ofstream::out | ofstream::app );

您也不需要调用close,因为这会在save 被破坏时自动发生。

关于c++ - 如何不覆盖文件,C++ 日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34916054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com