SKY外语计算机学习
标题:
对文件实现写入和读取功能
[打印本页]
作者:
愚昧儒生
时间:
2013-12-9 23:28
标题:
对文件实现写入和读取功能
请问谁能提供一段可以实现对.dat文件(二进制)写入和读取功能的代码。
本人正在学习怎样向文件实现写入后读取,希望有大神能提供帮助。
作者:
admin
时间:
2013-12-16 17:01
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct test
{
string name;
int id;
int age;
};
void print_test(const test &t)
{
cout << "Name: " << t.name << endl;
cout << "ID: " << t.id << endl;
cout << "Age: " << t.age << endl << endl;
}
int main()
{
test t[2];
ofstream out("out.dat", ios::out);
if (!out)
{
cerr << "File open error!";
return 1;
}
t[0].name = "Name1";
t[0].id = 101;
t[0].age = 20;
t[1].name = "Name2";
t[1].id = 102;
t[1].age = 25;
out.write((char*)t, sizeof(t));
out.close();
ifstream in("out.dat", ios::in);
if (!in)
{
cerr << "File open error!";
return 1;
}
vector<test> vt;
test tmp;
while (in.read((char*)&tmp, sizeof(test)))
{
vt.push_back(tmp);
if (in == NULL)
cout << "NULL";
}
vector<test>::iterator it;
for (it=vt.begin(); it!=vt.end(); ++it)
print_test(*it);
in.close();
return 0;
}
复制代码
作者:
愚昧儒生
时间:
2013-12-17 18:29
admin 发表于 2013-12-16 17:01
谢谢,我也写了个
#include<iostream>
#include<fstream>
using namespace std;
struct People
{
int num;
char name[18];
};
int main()
{
People peo[30];
int num;
char name[18];
int n;
cout<<"plese input the whole number"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"please input the num of people:"<<i+1<<endl;
cin>>peo[i].num;
cout<<"please input the name of people:"<<i+1<<endl;
cin>>peo[i].name;
}
fstream f("peo.dat",ios::out|ios::binary);
f.close();
f.open("peo.dat",ios::in|ios::out|ios::binary);
if(f.fail())
{
cout<<"error for open"<<endl;
exit(1);
}
f.write((char*)&peo[0],sizeof(People)*n);
People p;
f.seekp(0);
f.read((char*)&p,sizeof(People));
while(!f.eof())
{
cout<<endl<<p.num<<endl<<p.name<<endl<<endl;
f.read((char*)&p,sizeof(People));
}
f.close();
return 0;
}
复制代码
欢迎光临 SKY外语计算机学习 (http://join.skywj.com/)
Powered by Discuz! X2.5