Menu Close

Working with binary file

Working with binary file

1. namespace

The namespace System::IO is used to work with file reading and writing

 

 2. Save binary data into file

1). Create a file stream 

FileStream^ fs = gcnew FileStream(“BinaryFileName”, FileMode::CreateNew);

2). Create a writer for binary data

BinaryWriter^ wr = gcnew BinaryWriter(fs);

3). Write data to “BinaryFileName”. 

a). Create random data to write 
   array<Byte>^dataArray = gcnew array<Byte>(arrayLength);
   (gcnew Random)->NextBytes( dataArray );

b). Write one data to file

wr->Write(dataArray[0]);

c). Write Byte array: wr->Write( dataArray );

d). For other write method please refer to BinaryWriter Methods

 4). Close the BinaryWriter:        wr->Close();

5). Close the FileStream:        fs->Close();

 For save text to a file refer to here.

3. Read data from a binary file

 1). Check the file exists by using   File::Exists(“BinaryFileName “)

2). If the file exists, open the file

BinaryReader^ binReader = gcnew BinaryReader( File::Open(“BinaryFileName”, FileMode::Open ) );

3). Read data from the file

a). Read a number of bytes, e.g. 512 bytes

array<Byte>^updater = gcnew array<Byte>(512);

binReader->Read(updater, 0, 512 );

b). Read String

String^ lookupDir = binReader->ReadString();

c). For other read method please refer to BinarReader Methods

4). Reset the position in the stream to zero.
  binReader->BaseStream->Seek(0, SeekOrigin::Begin);

5) . Close the file

           binReader->Close.

For read text from a file refer to here

One comment on “Working with binary file

  1. Pingback: Working with text file | Code References

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

18,577 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>