该程序是C++的留言功能的程序,在向文件中进行第二次输出时,前次输出的内容被删掉,求解决方法
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
using namespace std;
class Mailman
{
public:
Mailman()
{
fstream outfile;
//system("mkdir");
outfile.open("C:\\msg.ini",ios::binary);
outfile.close();
name="00";
message="000000";
strcpy(dbuffer,"000");
strcpy(tbuffer,"00000");
}
void scan();
void print();
~Mailman(){}
//private:
string name;
string message;;
char dbuffer [9];
char tbuffer [9];
};
int main()
{
//void write_message();
Mailman mail[2];
/*filebuf *pbuf;
char * buffer;
ifstream infile;
infile.open("C:\\msg.ini",ios::binary);
if (! infile)
{
cerr << "Cannot open File!" << endl;
system("pause");
return 0;
}
pbuf=infile.rdbuf();
streampos filelength;
//infile.seekg(0,ios::end);
//filelength=infile.tellg();//long filelength=ifile.tellg();
filelength=pbuf->pubseekoff (0,ios::end,ios::in);
pbuf->pubseekpos (0,ios::in);
if(int(filelength)==0)
{
cout<<"File size:"<<filelength<<endl;
}
buffer=new char[filelength];// 分配内存空间
pbuf->sgetn (buffer,filelength);// 获取文件内容
infile.close();
cout.write (buffer,filelength);
delete []buffer;*/
char or;
for(int i=0;i<2;i++)
{
fstream outfile;
outfile.open("C:\\msg. ini",ios::binary|ios::end);
mail[i].scan();//mail.
_strdate(mail[i].dbuffer);
_strtime(mail[i].tbuffer);
outfile<<mail[i].name<<endl<<mail[i].message<<endl<<mail[i].dbuffer<<" "<<mail[i].tbuffer<<endl;
//outfile.write((char *)&mail[i],sizeof(mail[i]));
outfile.close();
cout<<"Do you want exit?(y/n)"<<endl;
cin>>or;
if(or=='y'||or=='Y')
{
exit(1);
}
else
continue;
outfile.seekp(-sizeof(mail[i]),ios::cur);
}
return 0;
}
void Mailman::scan()
{
cout<<"Enter the number"<<endl;
cout<<"Name:";
cin>>name;
cout<<"Message:";
//cin>>message;
getchar(); //提取前一个换行符
getline(cin,message,'\n');
}
void Mailman::print()
{
cout<<"Name:"<<name<<endl;
cout<<"Message:"<<'\n'<<message<<endl;
cout<<message<<endl;
}
/*void write_message()
{
outfile.open("C:\\msg. ini",ios::out);
mail.scan();//mail.
_strdate(mail.dbuffer);
_strtime(mail.tbuffer);
outfile<<mail.name<<endl<<mail.message<<endl<<mail.dbuffer<<" "<<mail.tbuffer<<endl;
outfile.close();
}*/
/*设计一个留言的类,实现以下功能:
1)程序为第一次运行时,建立一个名C\:msg. ini的文本文件,
并把用户输人的信息存人该文件
2)以后每次运行时,都先读取该文件的内容并显示给用户,然后由用户输人新的信息,
退出时将新的信息存人这个文档。文件的内容,既可以是最新的信息,也可以包括以前所有的信息,
请自己选择。
s定义一个类Mailman,在构造函数中检查"C:\mg.ini"文件的存在,如果不存在则创建之,如果存在则读取并显示内容给用户。
把用户输人的信息存放到程序中定义的缓冲区,请注意缓冲区一的大小。
用户退出时,询问是否要把留言写人,如果是则把信息写人文件。
*/
[解决办法]
打开文件的时候使用追加的方式。这样就可以在文件末尾进行写入。
- C/C++ code
infile.open("C:\\msg.ini",ios::binary|ios::app);
------解决方案--------------------
[解决办法]
靠,复制忘了改
FILE *fp = fopen("a.txt", "w");
[解决办法]
_strdate 是干什么的??
还有你的构造函数到底下个干嘛,构造函数打开,又不关闭,