这里以一个简单的学生信息管理系统为例。

  首先是对象的建立,包括姓名,学号,成绩,学分,等

  如下:

  这里面包括两个子对象,

 class Student
{
public:
Student() :score(), birthday(){}//对子对象进行初始化
~Student(){}
void InputInfo();
void OutPutInfo();
void ShowInfo();
bool CreditManage(); char *getNum(){ return num; }
char *getName(){ return name; }
bool getSex(){ return sex; }
float GetCredit(){ return credit; }
void swapStudent(Student &stu);
private:
char num[];
char name[];
bool sex;
Score score;//子对象
Birthday birthday;//子对象
float credit;
bool isChanged;
};

  然后主要还是文件读写。文件读写包括三个类,其中ifstream和ofstrean从fstream派生而来,可以在创建对象的时候直接初始化,这样比较方便。也可以使用open函数打开文件

    (1) ifstream类,它是从istream类派生的。用来支持从磁盘文件的输入。

    (2) ofstream类,它是从ostream类派生的。用来支持向磁盘文件的输出。

    (3) fstream类,它是从iostream类派生的。用来支持对磁盘文件的输入输出。

  其中的文件读写的关键函数是read和write,这两个函数可以读写固定长度的数据

     istream& read(char *buffer,int len);

     ostream& write(const char * buffer,int len);

  文件操作完毕一定要关闭文件,只需调用close()就行。

  如file.close();

  定义一个全局函数用于获取文件中对象的个数,

 int GetNumberFromFile()
{
int count = ;//对象个数,即学生人数
fstream infile("e:\\student.txt",ios::in | ios::binary);//以读方式打开文件
if (!infile)
{
cout<<"open file error!"<<endl;
getchar();
exit();
}
Student stu;
while (infile.read((char*)&stu,sizeof(stu)))//强制类型转换为(char*),
{
count++;
}
infile.close();
return count;
}

  这里的文件读写关键是在read函数,read函数会读取数据一直到文件结束

 basic_istream<Elem, Tr>& read(
char_type *_Str, //这里是要保存的对象数组的地址
streamsize _Count//这里是对象的大小
);

  因为数据是以二进制保存到文件中的,所以我们不用关心数据的格式,我们知道怎么读取数据就行了。向文件中写入整个对象的好处是将来可以整个读取出来进行操作,不必去考虑细节。

  写入文件和这个类似

             Student stu1;
stu1.InputInfo();
fstream outfile("e:\\student.txt", ios::app | ios::binary);//这里以app方式打开文件进行添加
if (!outfile)
{
cerr << "open file error!";
}
outfile.write((char*)&stu1, sizeof(stu1));
outfile.close();
以app方式打开文件进行添加,文件内部的位置指针会自动移动移动到文件末尾,直接添加文件到最后。

  当对文件进行输出时

             fstream infile("e:\\student.txt",ios::in | ios::binary);
if (!infile)
{
cout<<"open file error!"<<endl;
getchar();
//exit(0);
}
int len = ;
len = GetNumberFromFile();
if (len == )
{
cout << "no data!" << endl;
ch = '';
break;
}
Student *stu = new Student[len];//动态申请地址,因为这个数组大小是在运行过程中才能知道的
cout << "number\tname\tsex\tyear-month-day\tcredit" << endl;
for (int i = ; i < len;i++)
{
infile.read((char*)&stu[i], sizeof(stu[i]));
stu[i].OutPutInfo();
}
delete []stu;
infile.close();

  

还有一些排序的简单实现在下面的代码中

整个程序代码在这里

 #include <iostream>
#include "string"
using namespace std; class Student;
bool SortByCondition(Student stu[],const int &len,const char &conditon);//排序
void SaveToFile(Student stu[],int num);
void ReadFromFile(Student stu[],int num);
int GetNumberFromFile();
char Menu();
char SortMenu(); class Score
{
public:
Score(){ english = , math = ; computer = ; }
Score(float eng, float mat, float com) :english(eng), math(mat), computer(com){}
void InputScore()
{
cout << "enter english score:";
cin>> english;
cout << "enter math score:";
cin >> math;
cout << "enter computer score:";
cin >> computer;
}
void outputScore()
{
cout << english << "\t" << math << "\t" << computer << "\t";
}
float ScoreSum()
{
return (math + english + computer);
}
void swapScore(Score &scor)//对象交换数据
{
float ftmp = english;
english = scor.english;
scor.english = ftmp; ftmp = math;
math = scor.math;
scor.math = ftmp; ftmp = computer;
computer = scor.computer;
scor.computer = ftmp;
}
private:
float english;
float math;
float computer;
}; class Birthday
{
public:
Birthday(){ year = ; month = ; day = ; }
Birthday(int ye, int mon, int da) :year(ye), month(mon), day(da){}
void inputBirthday()
{
cout << "enter birthday like \"2014 05 01\":" << endl;
cin >> year >> month >> day;
}
void outputBirthday()
{
cout << year << "\-" << month << "\-" << day << "\t";
}
void swapBirthday(Birthday &bir)//对象交换数据
{
int itmp = year;
year = bir.year;
bir.year = itmp; itmp = month;
month = bir.month;
bir.month = itmp; itmp = day;
day = bir.day;
bir.day = itmp;
}
private:
int year;
int month;
int day;
}; class Student
{
public:
Student() :score(), birthday(){}
~Student(){}
void InputInfo();
void OutPutInfo();
void ShowInfo();
bool CreditManage(); char *getNum(){ return num; }
char *getName(){ return name; }
bool getSex(){ return sex; }
float GetCredit(){ return credit; }
void swapStudent(Student &stu);//对象交换数据
private:
char num[];
char name[];
bool sex;
Score score;
Birthday birthday;
float credit;
bool isChanged;
};

student.h

 #include "student.h"
#include "iostream"
#include "fstream"
using namespace std; void Student::InputInfo()
{
cout << "enter number(字符串)";
cin >> num;
cout << "enter name(字符串)";
cin >> name;
cout << "enter sex(0表示女,1表示男)";
cin >> sex;
score.InputScore();
birthday.inputBirthday();
credit = score.ScoreSum() / ;//计算得出学分
} void Student::OutPutInfo()
{
cout << num << "\t" << name << "\t" << sex << "\t";
//score.outputScore();
birthday.outputBirthday();
cout << credit << endl;
} char Menu()
{
//system("cls");
cout << "******************************************" << endl;
cout << "***welcome to student management system***" << endl;
cout << "******************************************" << endl;
cout << "please choose the number below:" << endl;
cout << "1--成绩录入" << endl;
cout << "2--成绩显示" << endl;
cout << "3--排序管理" << endl;
cout << "4--学分管理" << endl;
cout << "0--退出" << endl;
char ch = getchar();
return ch;
} void Student::swapStudent(Student &stu)
{
char tmp[];
strcpy_s(tmp, num);
strcpy_s(num, stu.num);
strcpy_s(stu.num, tmp); char nam[];
strcpy_s(nam, name);
strcpy_s(name, stu.name);
strcpy_s(stu.name, nam); bool btmp = sex;
sex = stu.sex;
stu.sex = btmp; score.swapScore(stu.score);
birthday.swapBirthday(stu.birthday); float ftmp = credit;
credit = stu.credit;
stu.credit = ftmp; btmp = isChanged;
isChanged = stu.isChanged;
stu.isChanged = btmp; } char SortMenu()
{
cout << "选择要进行排序的方式:";
cout << "1--学号" << endl;
cout << "2--姓名" << endl;
cout << "3--性别" << endl;
cout << "4--学分" << endl;
cout << "5--返回上一级" << endl;
getchar();
char ch = getchar();
return ch;
} bool SortByCondition(Student stu[], const int &len, const char &conditon)//排序
{
char tmp = conditon;
int length = len;
switch (tmp)
{
case ''://学号
{
for (int i = ; i < length; i++)
{
for (int j = ; j < length-i-; j++)
{
if (strcmp((stu[j].getNum()), stu[j + ].getNum()) > )
//if (stu[j].getName().compare(stu[j+1].getName()) > 0)
{
//compare(stu[j].getName(),stu[j+1].getName());
//stu[j].getName().compare(stu[j+1].getName());
stu[j].swapStudent(stu[j + ]);
}
}
}
cout << "学号降序排列" << endl;
for (int i = ; i < length; i++)
{
stu[i].OutPutInfo();
// if (i % 10 == 0)
// {
// cout << "按下任意键继续显示" << endl;
// getchar();
// }
}
getchar();
}
break;
case ''://姓名
{
for (int i = ; i < length; i++)
{
for (int j = ; j < length - i - ; j++)
{
if (strcmp(stu[j].getName(), stu[j + ].getName()) < )
//if (stu[j].getNum().compare(stu[j+1].getNum()) > 0)
{
stu[j].swapStudent(stu[j + ]);
}
}
}
cout << "姓名降序排列" << endl; for (int i = ; i < length; i++)
{
stu[i].OutPutInfo();
// if (i % 10 == 0)
// {
// cout << "按下任意键继续显示" << endl;
// getchar();
// }
}
getchar();
}
break;
case ''://性别
{
for (int i = ; i < length; i++)
{
for (int j = ; j < length - i - ; j++)
{
if (stu[j].getSex() < stu[j + ].getSex())
{
stu[j].swapStudent(stu[j + ]);
}
}
}
cout << "性别降序排列" << endl;
for (int i = ; i < length; i++)
{
stu[i].OutPutInfo();
// if (i % 10 == 0)
// {
// cout << "按下任意键继续显示" << endl;
// getchar();
// }
}
getchar();
}
break; case ''://学分
{
for (int i = ; i < length; i++)
{
for (int j = ; j < length - i - ; j++)
{
if (stu[j].GetCredit() < stu[j + ].GetCredit())
{
stu[j].swapStudent(stu[j + ]);
}
}
}
cout << "学分降序排列" << endl;
for (int i = ; i < length; i++)
{
stu[i].OutPutInfo();
// if (i % 10 == 0)
// {
// cout << "按下任意键继续显示" << endl;
// getchar();
// }
}
getchar();
}
break;
default:
break;
}
return true;
} int GetNumberFromFile()
{
int count = ;//对象个数,即学生人数
fstream infile("e:\\student.txt",ios::in | ios::binary);
if (!infile)
{
cout<<"open file error!"<<endl;
getchar();
exit();
}
Student stu;
while (infile.read((char*)&stu,sizeof(stu)))
{
count++;
}
infile.close();
return count;
}

student.cpp

 #include "student.h"
#include "fstream"
#include "string" int main()
{
char ch = Menu();
int quit = ;
while (quit)
{
switch (ch)
{
case ''://成绩录入
{
Student stu1;
stu1.InputInfo();
fstream outfile("e:\\student.txt", ios::app | ios::binary);
if (!outfile)
{
cerr << "open file error!";
}
outfile.write((char*)&stu1, sizeof(stu1));
outfile.close(); ch = '';
getchar();
}
break;
case ''://成绩显示
{
fstream infile("e:\\student.txt",ios::in | ios::binary);
if (!infile)
{
cout<<"open file error!"<<endl;
getchar();
//exit(0);
}
int len = ;
len = GetNumberFromFile();
if (len == )
{
cout << "no data!" << endl;
ch = '';
break;
}
Student *stu = new Student[len];
cout << "number\tname\tsex\tyear-month-day\tcredit" << endl;
for (int i = ; i < len;i++)
{
infile.read((char*)&stu[i], sizeof(stu[i]));
stu[i].OutPutInfo();
}
delete []stu;
infile.close();
ch = '';
getchar();
}
break;
case ''://排序管理
{
char condtion = SortMenu();
fstream file("e:\\student.txt", ios::in | ios::binary);
if (!file)
{
cerr << "open file error!";
}
int len = GetNumberFromFile();
Student *stu = new Student[len];
for (int i = ; i < len;i++)
{
file.read((char *)&stu[i], sizeof(stu[i]));
} file.close();
SortByCondition(stu,len, condtion); delete []stu;
getchar();
}
break; case ''://学分管理
{ }
break; case '':
{
quit = ;
exit();
ch = '';//quit switch
}
break;
default:
//ch = '0';
break;
}
//getchar(); ch = Menu();
}
system("pause");
return ;
}

main.cpp

C++文件读写之对象的读写的更多相关文章

  1. Objective-C 【从文件中读写字符串(直接读写/通过NSURL读写)】

    ———————————————————————————————————————————从文件中读写字符串(直接读写/通过NSURL读写) #import <Foundation/Foundati ...

  2. Golang的文件处理方式-常见的读写姿势

    Golang的文件处理方式-常见的读写姿势 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在 Golang 语言中,文件使用指向 os.File 类型的指针来表示的,也叫做文件句柄 ...

  3. Delphi开发的数据库程序在C:\PDOXUSRS.NET生成文件,拒绝访问及读写权限

    Delphi开发的数据库程序在C:\PDOXUSRS.NET生成文件,拒绝访问及读写权限, "无法打开 PARADOX.NET.这个文件可以随便删除的,下次会自动产生. Permission ...

  4. Java第三十四天,IO操作(续集),非基本对象的读写——序列化流

    一.序列化与反序列化 以前在对文件的操作过程当中,读写的对象都是最基本的数据类型,即非引用数据类型.那么如果我们对饮用数据类型(即对象类型)数据进行读写时,应该如何做呢?这就用到了序列化与反序列化. ...

  5. java 输入输出IO流 RandomAccessFile文件的任意文件指针位置地方来读写数据

    RandomAccessFile的介绍: RandomAccessFile是Java输入输出流体系中功能最丰富的文件内容访问类,它提供了众多的方法来访问文件内容,它既可以读取文件内容,也可以向文件输出 ...

  6. Android NFC M1卡读写&芯片卡读写(CPU卡读写)(RFID读写)

    版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/sgn5200/article/detai ...

  7. Java对文件中的对象进行存取

    1.保存对象到文件中 Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可: public static void writeObjectToFile(Obje ...

  8. OpenCV C++ 计算文件夹中对象文件数目及批量处理后保存到txt文件

    //采用windows控制台实现计算文件夹中对象总数以及批量读取对象 //#include <afx.h> //和windows.h是一样的作用 #include <opencv2/ ...

  9. 关于Android Assets读取文件为File对象

    关于Android Assets读取文件为File对象的问题,在Assets里面放置文件,在使用的时候,一般是使用AssetManger对象,open方法获取InputStream 然后进行其他操作. ...

随机推荐

  1. Android接入支付宝支付实现

    接上篇android接入微信支付文章,这篇我们带你来接入支付宝支付服务 简介 首先要说明的是个人感觉接入支付宝比微信简单多了,很轻松的,所以同学们不要紧张~ 当然还是老规矩啦,上来肯定的贴上官网地址, ...

  2. SQL解读XML案例

    ALTER PROCEDURE [dbo].[GetProductList1] @Products XML AS BEGIN SET NOCOUNT ON DECLARE @Pointer INT D ...

  3. MVC下c#对接微信公众平台开发者模式

    在ashx文件中进行HttpContext的处理: using System; using System.Collections.Generic; using System.Linq; using S ...

  4. PHP与MYSQL结合操作——文章发布系统小项目(实现基本增删查改操作)

    php和mysql在一起几十年了,也是一对老夫老妻了,最近正在对他们的爱情故事进行探讨,并做了一个很简单的小东西——文章发布系统,目的是为了实现mysql对文章的基本增删查改操作 前台展示系统有:文章 ...

  5. Redis单机数据库

    单机数据库 ·Redis服务器的所有数据库都保存在redisServer.db数组中,而数据库的数量则由redisServer.dbnum属性保存. ·客户端通过修改目标数据库指针,让它指向redis ...

  6. python_33_文件操作2

    f=open('yesterday',encoding='utf-8') #print(f.readline())#读一行,并且是第一行 #读前5行 for i in range(5):#range( ...

  7. SpringMVC+Hibernate框架快速搭建

    1.  新建Maven项目springmvc 2.   pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" ...

  8. Drupal相关网站推荐

    http://nodeone.se/ drupal7安装过程中,如果选择简体中文,到导入翻译时出现错误,原因是执行超时了. 方法一: 修改php.ini文件:memory_limit = 256M ( ...

  9. 基于 Nginx && Lua 的简易CC防护方案

    零.前言 1.CC攻击简述 CC攻击(Challenge Collapsar)是常见网站应用层攻击的一种,目的是消耗服务器资源,降低业务响应效率:极端情况会让站点无法正常提供服务: 2.本文要点 旨在 ...

  10. [未完] term.js 记录遇到的问题

    参考博文:https://www.cnblogs.com/zhenfei-jiang/p/7065038.html 按照网上查找的资料敲了代码 term.on('data', function(dat ...