65,206
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int load();
int save(int &b);
int main()
{
int c;
for(int i = 0;i < 3; i++)
{
cin >> c;
save(c);
load();
}
system("pause");
return 0;
}
int load()
{
ifstream fin;
fin.open("file.txt",ios::binary);
if(!fin)
{
cout << "can't open the file!" << endl;
return 0;
}
int a;
while(!fin.eof())
{
if (fin.read((char*)&a,sizeof(int))) //注意这里,当最后一个数据读出的时候
//文件还没有结束,再读的时候才结束...所以最好是自己判断
cout << a <<endl;
};
fin.close();
return 1;
}
int save(int &b)
{
ofstream fout;
fout.open("file.txt",ios::app |ios::binary);
if(!fout)
{
cout << "can't open the file!" <<endl;
return 0;
}
fout.write((const char*)&b,sizeof(int));
fout.close();
cout << "write into the file successful!" << endl;
}