from fread to std::ifstream

Started by
3 comments, last by Trillian 18 years, 2 months ago
Hello! I'm trying to "update" my code from the old c libraries to the new c++ ones. I have a loader class for 3ds files, and since I made the switch, nothing works anymore (I still have a backup don't worry ;). 3DS files are organised in unsigned short chunks, and the first one (at the very beginning of the file) should always be the MAIN_CHUNK (0x4D4D). But now the first thing read is 13103 (0x332F), so it must be that I am using ifstream badly. first of all, I open the file like this :
m_File.open(filename,std::ios::in | std::ios::binary);
I chek if the file is_open() and it is, no problem there. The next thing I do is to position the file pointer at the beginning, even if that should already be the case :
m_File.seekg(std::ios::beg);
Then I chek if the file is good() and it is. I read the chunk header like this (the fread way is commented):

BGL::CBGL3dsLoader::SChunkHeader BGL::CBGL3dsLoader::ReadHeader()
{
	unsigned short usiChunkID;
	unsigned long uiChunkLength;
	//fread(&usiChunkID, 2, 1, m_File);    //Read the header
	//fread(&uiChunkLength, 4, 1, m_File); //Read the lenght
	m_File >> usiChunkID;
	m_File >> uiChunkLength;
	return SChunkHeader(usiChunkID,uiChunkLength);
}



But then, the fread way and the ifstream >> way doesnt give the same results! Im I doing something wrong?
Advertisement
I'm pretty sure that it thinks you're trying to read 8-bit text data, so use ifstream::read() instead. otherwise, you'll need to create a new class that inherits std::istream (or std::ifstream) and override the >> operator to read binary data.
std::ifstream::read() asks for a char * and a number of chars to be read.

would this work:
unsigned int foo;myifstream.read((char*)&foo,sizeof(foo));

Would that give me a corrupted int, as it is read byte by byte?
I don't see why it would do that, just checking to be sure.
Quote:Original post by Trillian
std::ifstream::read() asks for a char * and a number of chars to be read.

would this work:
unsigned int foo;myifstream.read((char*)&foo,sizeof(foo));

Would that give me a corrupted int, as it is read byte by byte?
I don't see why it would do that, just checking to be sure.


provided you are sure of the endian-ness of the data being read, it shouldn't affect it at all.
Ok thanks for your help!

EDIT : Guess what... it actually worked!

This topic is closed to new replies.

Advertisement