I/O :文件流

来源:互联网 发布:大隅级两栖攻击舰 数据 编辑:程序博客网 时间:2024/05/02 01:48

首先搞清流的输入输入出

图解:
这里写图片描述

  1. ifstream: 搞出的是输入文件流对象
  2. ofstream: 搞出的是输出文件流对象

fstream 输入输出文件流

#include <iostream>#include <fstream>#include <cstdlib>#include <cstring>using namespace std;struct Student{    char name[10];    char num[20];    int age;};void disp_all(Student *t, int len){    cout << "---------------------" << endl;    for(int i=0; i<len; i++)    {        cout << "number: " << (t+i)->num << endl;        cout << "name: " << (t+i)->name << ", age: " << (t+i)->age << endl;    }}void disp(Student *t){    cout << "number: " << t->num << endl;    cout << "name: " << t->name << ", age: " << t->age << endl;}int main(){    Student stu[5] = {        "Larry", "1221010", 18,        "DaWei", "1221011", 18,        "LiLi", "1221012", 20,        "PaPa", "1221013", 19,        "HuoFu","1221014", 10,    };    //这种方式不会默认的创建文件    fstream iofile("file/save2.dat", ios::in|ios::out|ios::binary);    if(!iofile)    {        cerr<< "open error" << endl;        abort();//与exit()的作用相同    }    // 作用: 将stu中的5个元素写到磁盘文件中    for(int i=0; i<5; i++)        iofile.write((char *)&stu[i], sizeof(Student));    Student g[5] = {0};    //作用: 将文件中的5个元素读入内存    iofile.seekg(0, ios::beg);//将文件指针指向文件开头    for(int i=0; i<5; i++)    {        iofile.read((char *)&g[i], sizeof(g[i]));        cout << iofile.tellg() << endl;    }    disp_all(g, 5);    strcpy(stu[2].name,"huahua");    strcpy(stu[2].num, "1234" );    stu[2].age = 12;    //将一个stu元素放在文件开头指定个字节处    iofile.seekp(2*sizeof(Student), ios::beg);    iofile.write((char *)&stu[2], sizeof(Student));    iofile.seekg(2*sizeof(Student), ios::beg);    iofile.read((char *)&g[2], sizeof(Student));    disp_all(g, 5);    iofile.close();    return 0;}

下面这个在重载输入流的时候用过
cin 流出错
if(cin) ….


标准输出流里
cout.unsetf(ios::dex); //关掉10进制
cout.setf(ios::showbase); //在进制前加上大小写字母

0 0
原创粉丝点击