Visual C++ .NET/File Directory/BinaryWriter — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:05, 26 мая 2010
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 = DateTime( br->ReadInt64() );
br->Close();
fs->Close();
}
void main(){
Role ^r = gcnew Role("r", 10, true);
r->Save("Role.dat");
Console::WriteLine("Original r");
r->Print();
Role ^rClone = gcnew Role();
rClone->Load("Role.dat");
Console::WriteLine("\nCloned r");
rClone->Print();
}