Qbasicnews.com
File Input Question - Printable Version

+- Qbasicnews.com (http://qbasicnews.com/newforum)
+-- Forum: General (http://qbasicnews.com/newforum/forum-6.html)
+--- Forum: General/Misc (http://qbasicnews.com/newforum/forum-18.html)
+---- Forum: General Programming (http://qbasicnews.com/newforum/forum-20.html)
+---- Thread: File Input Question (/thread-9002.html)



File Input Question - Radical Raccoon - 03-10-2006

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?


File Input Question - shiftLynx - 03-10-2006

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]


File Input Question - Radical Raccoon - 03-10-2006

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?


File Input Question - shiftLynx - 03-10-2006

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#.