Best way to Read Binary Files

M

Marc Ouellette

Hi Everyone,

I am currently reading Binary files in C++Builder using the code below.
Removed some error chacking to make the code simpler to read.

std::ifstream fin;
fin.open(filename.c_str(), std::ios::in|std::ios::binary);
// read the image from file into memory
fin.read((char *)ptr, sizeof(T) * numCells);
fin.close();


I am new to C# and would like to read the same file. In the case above T is
an short.

What would be the quickest way to read it if I already know how many shorts
to read(numCells) and what is the C++ short to C# equivalent(int)?

Thanks,
Marc
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

The way of doing it in C# is similar, just use FileStream
 
S

Samuel R. Neff

One thing that's very different in C# vs C++ is that in C# you
generally do not read in a large block of data and simply assign it to
memory and then give it a type or structure. In C# you'll either use
a BinaryReader class to read in individual primitive types at a time
or use binary serialization.

You can also use either the BinaryReader or any stream to read raw
bytes into a byte array and then copy the data to appriately typed
members. With unsafe code within c# you can do direct assignment, but
that is generally avoided when not necessary.

A signed short in c++ would be a System.Int16 or "short" in c#. An
unsigned short would be System.UInt16 or "ushort".

HTH,

Sam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top