设为首页收藏本站

SKY外语、计算机论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 5163|回复: 1
打印 上一主题 下一主题

[C++] 对文件实现写入和读取功能

[复制链接]

2

主题

0

好友

157

积分

注册会员

Rank: 2

星座
摩羯座
性别

最佳新人

跳转到指定楼层
楼主
发表于 2013-12-9 23:28:36 |显示全部楼层 |倒序浏览
请问谁能提供一段可以实现对.dat文件(二进制)写入和读取功能的代码。
本人正在学习怎样向文件实现写入后读取,希望有大神能提供帮助。
分享到: QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
分享淘帖0 收藏收藏0 评分评分

2

主题

0

好友

157

积分

注册会员

Rank: 2

星座
摩羯座
性别

最佳新人

沙发
发表于 2013-12-17 18:29:32 |显示全部楼层
admin 发表于 2013-12-16 17:01

谢谢,我也写了个
  1. #include<iostream>
  2. #include<fstream>
  3. using namespace std;
  4. struct People
  5. {
  6.         int num;
  7.         char name[18];
  8. };

  9. int main()
  10. {
  11.         People peo[30];
  12.         int num;
  13.         char name[18];
  14.         int n;
  15.         cout<<"plese input the whole number"<<endl;
  16.     cin>>n;


  17.         for(int i=0;i<n;i++)
  18.         {
  19.                 cout<<"please input the num of people:"<<i+1<<endl;
  20.                 cin>>peo[i].num;
  21.                 cout<<"please input the name of people:"<<i+1<<endl;
  22.                 cin>>peo[i].name;
  23.         }


  24.         fstream f("peo.dat",ios::out|ios::binary);
  25.         f.close();

  26.         f.open("peo.dat",ios::in|ios::out|ios::binary);
  27.         if(f.fail())
  28.         {
  29.                 cout<<"error for open"<<endl;
  30.                 exit(1);
  31.         }


  32.     f.write((char*)&peo[0],sizeof(People)*n);

  33.         People p;
  34.         f.seekp(0);
  35.         f.read((char*)&p,sizeof(People));
  36.         while(!f.eof())
  37.         {
  38.                 cout<<endl<<p.num<<endl<<p.name<<endl<<endl;
  39.                 f.read((char*)&p,sizeof(People));
  40.         }
  41.         f.close();
  42.         return 0;
  43. }
复制代码
回复

使用道具 评分 举报

您需要登录后才可以回帖 登录 | 立即注册


手机版|SKY外语计算机学习 ( 粤ICP备12031577 )    

GMT+8, 2024-5-7 06:37 , Processed in 0.117384 second(s), 27 queries .

回顶部