Qbasicnews.com

Full Version: File Input Question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I read in integers when all my file handling class does is read in bytes? I usually have to code some big function that takes in 2 bytes and returns an int. Are they any cool shortcut tricks that I should know about?
Use the read method of istream. Example:

[syntax="C"]
#include <iostream>
#include <fstream>
#include <stdint.h>

int main( int argc, char** argv )
{
std::ifstream myFile( "binfile.txt", std::ios::in | std::ios::binary );
if( myFile.bad() )
{
std::cerr << "Failed to open binfile.txt." << std::endl;
return 1;
}


uint16_t i = 0;
myFile.read( reinterpret_cast< char* >( &i ), sizeof( i ) );

std::cout << "Read in the value: " << i << std::endl;

myFile.close();

return 0;
}
[/syntax]
hmm, I failed to mention that I'm using C#

Maybe the technique is the same. Here's the function I'm using:

[syntax="C"]Read(byte[] array, int offset, int count)[/syntax]

What excatly are you doing with your code? Casting an int to a char to read it in or something? I've never seen "reinterpret_cast" before.

Got anything else I can try?
reinterpret_cast is the "proper" way to cast a pointer in C++. In C, the only casting was done through brackets, but C++ has different, more specialised casting methods: static_cast, reinterpret_cast, dynamic_cast, const_cast, ...

Sorry, I don't know C#.