Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File Input Question
#1
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?
Reply
#2
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]
img]http://www.cdsoft.co.uk/misc/shiftlynx.png[/img]
Reply
#3
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?
Reply
#4
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#.
img]http://www.cdsoft.co.uk/misc/shiftlynx.png[/img]
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)