设为首页收藏本站

SKY外语、计算机论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 5162|回复: 0
打印 上一主题 下一主题

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

[复制链接]

200

主题

3

好友

2253

积分

管理员

Rank: 9Rank: 9Rank: 9

性别
保密

热心会员 推广达人 宣传达人 灌水之王 突出贡献 优秀版主 荣誉管理 论坛元老 最佳新人 活跃会员

楼主
发表于 2013-12-16 17:01:50 |显示全部楼层
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. using namespace std;

  6. struct test
  7. {
  8.     string name;
  9.     int id;
  10.     int age;
  11. };

  12. void print_test(const test &t)
  13. {
  14.     cout << "Name: " << t.name << endl;
  15.     cout << "ID: " << t.id << endl;
  16.     cout << "Age: " << t.age << endl << endl;
  17. }

  18. int main()
  19. {
  20.     test t[2];
  21.     ofstream out("out.dat", ios::out);
  22.     if (!out)
  23.     {
  24.         cerr << "File open error!";
  25.         return 1;
  26.     }

  27.     t[0].name = "Name1";
  28.     t[0].id = 101;
  29.     t[0].age = 20;
  30.     t[1].name = "Name2";
  31.     t[1].id = 102;
  32.     t[1].age = 25;

  33.     out.write((char*)t, sizeof(t));
  34.     out.close();

  35.     ifstream in("out.dat", ios::in);
  36.     if (!in)
  37.     {
  38.         cerr << "File open error!";
  39.         return 1;
  40.     }

  41.     vector<test> vt;
  42.     test tmp;
  43.     while (in.read((char*)&tmp, sizeof(test)))
  44.     {
  45.         vt.push_back(tmp);
  46.         if (in == NULL)
  47.             cout << "NULL";
  48.     }

  49.     vector<test>::iterator it;
  50.     for (it=vt.begin(); it!=vt.end(); ++it)
  51.         print_test(*it);

  52.     in.close();
  53.    
  54.     return 0;
  55. }
复制代码
回复

使用道具 评分 举报

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


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

GMT+8, 2024-5-7 02:22 , Processed in 0.119151 second(s), 26 queries .

回顶部