1. 程式人生 > >C++檔案操作寫入和讀取結構體型別

C++檔案操作寫入和讀取結構體型別

// file2.cpp : 定義控制檯應用程式的入口點。
//
#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;
struct Student{
    int num;
    char name[20];
    };
int addInFile()
    {
    ofstream outFile("botao.dat",ios::out|ios::binary);  //定義檔案輸出流   檔案不存在時建立檔案
    //對檔案開啟錯誤時的操作
    if(!outFile)
        {
        cout<<"The file open error!"<<endl;
        return 0;
        }
    else        //檔案正常開啟時,進行相應的處理
        {
        Student *s=new Student;
        cout<<"輸入學生學號:";
        cin>>s->num;
        cout<<"輸入學生姓名:";
        cin>>s->name;
        outFile.write((char*)s,sizeof(Student));   //檔案輸出流向檔案中寫入student資訊
        }
    outFile.close();   //關閉輸出流
    return 1;
    }
int myReadFile()
    {
    ifstream inFile("botao.dat",ios::in|ios::binary);   //檔案輸入流  將檔案中的student資訊讀出到螢幕上
    //對檔案開啟錯誤時的操作
    if(!inFile)
        {
        cout<<"The inFile open error!"<<endl;
        return 0;
        }
    else
        {
        Student *s=new Student;
        inFile.read((char*)s,sizeof(Student));
        cout<<"學號:"<<s->num<<endl;
        cout<<"姓名:"<<s->name<<endl;
        }
    inFile.close();       //關閉輸入流
    }
int main()
    {
    cout<<"The main .............."<<endl;
    //addInFile();  //新增結構體
    myReadFile();  //讀取結構體
    return 0;
    }
http://botao900422.blog.51cto.com/4747129/1206950