Binary read and write with BinaryWriter and BinaryReader : BinaryWriter « File Directory « Visual C++ .NET

Home
Visual C++ .NET
1.2D
2.Class
3.Collections
4.Data Type
5.Database ADO.net
6.Delegate
7.Development
8.File Directory
9.Function
10.Generics
11.GUI Form
12.Language Basics
13.Network
14.Reflection
15.Security
16.Statement
17.Structure
18.Thread
19.XML
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Visual C++ .NET » File Directory » BinaryWriter 
Binary read and write with BinaryWriter and BinaryReader
 

#include "stdafx.h"
using namespace System;
using namespace System::IO;


ref class Role
{
    String ^Name;
    Int32   Strength;
    Boolean IsMale;
    DateTime CreateDate;

public:
    Role();
    Role (String ^Name, int Str, bool IsMale);

    void Print();
    void Save(String ^fname);
    void Load(String ^fname);
};

Role::Role()
{
}

Role::Role (String ^Name, int Str, bool IsMale)
{
    this->Name     = Name;
    this->Strength = Str;
    this->IsMale   = IsMale;
    this->CreateDate = DateTime::Now;
}

void Role::Print()
{
    Console::WriteLine("Name: {0} ({1})", Name, (IsMale ? "M" "F"));
    Console::WriteLine("Str:  {0}", Strength);
    Console::WriteLine("Date: {0}", CreateDate.ToString());
}

void Role::Save(String ^fname)
{
    FileStream   ^fs = File::OpenWrite(fname);
    BinaryWriter ^bw = gcnew BinaryWriter(fs);

    bw->Write(Name);
    bw->Write(Strength);
    bw->Write(IsMale);
    bw->Write(CreateDate.Ticks);  

    bw->Close();
    fs->Close();
}

void Role::Load(String ^fname)
{
    FileStream   ^fs = File::OpenRead(fname);
    BinaryReader ^br = gcnew BinaryReader(fs);

    Name     = br->ReadString();
    Strength = br->ReadInt32();
    IsMale   = br->ReadBoolean();

    CreateDate = DateTimebr->ReadInt64() );

    br->Close();
    fs->Close();
}

void main(){
    Role ^r = gcnew Role("r"10true);
    r->Save("Role.dat");

    Console::WriteLine("Original r");
    r->Print();

    Role ^rClone = gcnew Role();
    rClone->Load("Role.dat");

    Console::WriteLine("\nCloned r");
    rClone->Print();
}

   
  
Related examples in the same category
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.