• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
mynameisnafe

C++ Binary Parsing - ifstream reading different types

9 posts in this topic

Hi Guys,

I've got some silly questions about some basic IO stuff I should probably know to be fair.

I'm using ifstream to access a binary file for read.

My question is, how do I read different types, using fstream? Am I stuck to char arrays?

It's a 3ds file, so it's hierarchically chunked, with headers and bodies. I need to be able to read x amount of bytes, and convert it to a given type, i.e. an unsigned short or an unsigned int, or an array of floats, or even chars, say.

Can I use something like the following?

[CODE]
void*
Parser::temp_buffer;
// ..read two bytes into the buffer.. somehow without passing a char*
// then..
chunk->ID = (unsigned short) temp_buffer ;
[/CODE]

Or do I just have to wrap up a bunch of FILE* and fread functionality to do this?

Also, how do I store the current file pointer position as a member of a static class?

Thanks in advance :)
0

Share this post


Link to post
Share on other sites
[url=http://www.cplusplus.com/reference/istream/istream/read/]istream::read[/url] and [url=http://www.cplusplus.com/reference/istream/istream/seekg/]istream::seekg[/url] are what you're looking for:
[code]
unsigned short id;
in.read((char*)&id, sizeof(id));
[/code]

You can cut down the amount of repetitive code by using a template function:
[code]
template<class T>
istream& read_binary( istream& in, T& val ) {
in.read( (char*)&val, sizeof(val) );
return in;
}

void test(istream& file) {
short id;
read_binary( file, id );
}
[/code]
1

Share this post


Link to post
Share on other sites
Be aware that istreams are formatted input streams.Trying to use one to read unformatted data is a bit offlabel.

Yu might want to pull from a file using a std::streambuf instead, it's job is to pull data from a file and make it available as a stream of bytes.
0

Share this post


Link to post
Share on other sites
[quote name='fastcall22' timestamp='1354829854' post='5007887']
[url="http://www.cplusplus.com/reference/istream/istream/read/"]istream::read[/url] and [url="http://www.cplusplus.com/reference/istream/istream/seekg/"]istream::seekg[/url] are what you're looking for:
[code]
unsigned short id;
in.read((char*)&id, sizeof(id));
[/code]

You can cut down the amount of repetitive code by using a template function:
[code]
template<class T>
istream& read_binary( istream& in, T& val ) {
in.read( (char*)&val, sizeof(val) );
return in;
}

void test(istream& file) {
short id;
read_binary( file, id );
}
[/code]
[/quote]

that looks G! Thank you :)
0

Share this post


Link to post
Share on other sites
Okay, that template function is sweet! Thanks :)

I've now got a question about std::cout. I'm printing out some info for debugging (ID, SIZE, mSTART, END), like so:

[CODE]
static void PrintChunk( BinaryFileMapChunk* chunk ) {
std::cout
<< "\n Type: " << std::hex << chunk->TYPE << std::endl;
std::cout
<< "\n Size: " << (unsigned int) chunk->SIZE
<< "\n Start Pos: " << (unsigned int) chunk->START
<< "\n End Pos: " << (unsigned int) chunk->END;
}
[/CODE]


The issue is this line:
[CODE] std::cout << "\n Type: " << std::hex << chunk->TYPE << std::endl[/CODE]

It seems that this line makes all my output come out as hex, if I remove the [CODE]std::hex[/CODE] itall comes out fine except the ID value which I'd like to see as hex isn't hex so it's not very useful to me..

What's going on?
0

Share this post


Link to post
Share on other sites
std::hex keeps in effect until you stick in another base field formatter. So if you want to go back to decimal stick in a [tt]<< std::dec[/tt] before the next number you want to be in decimal.
1

Share this post


Link to post
Share on other sites
I find that the 'sticky' behaviour of std::hex is rarely something I want. I usually have something like this reinvented in every project I work on that makes use of iostreams:

[code]
#include <iostream>
#include <iomanip>


template<typename T>
struct as_hex_wrapper
{
as_hex_wrapper(T n) : n(n) { }
T n;
};

template<typename T>
as_hex_wrapper<T> as_hex(T n) { return as_hex_wrapper<T>(n); }

template<typename T>
std::ostream &operator<< (std::ostream &out, const as_hex_wrapper<T> &ahw)
{
// TODO: should really restore previous base and showbase settings
return out << std::hex << std::showbase << ahw.n << std::noshowbase << std::dec;
}

// -------------

int main()
{
const unsigned n = 0xDeadBeef;
std::cout << as_hex(n) << std::endl;
return 0;
}
[/code]

std::showbase gives you the leading "0x", which I almost always want when displaying anything other than a stream of bytes in hex.
1

Share this post


Link to post
Share on other sites
Thats some cool looking code - I'm slowly getting exposed to more stuff like this [CODE]as_hex_wrapper(T n) : n(n) { }[/CODE].

I decided to use std::hex and std::dec in my print function, as it's only there to debug with. Thanks :)

The next issue I've run into is what to do when you know the next 'few' bytes are a string but you don't know how long that string is..

Do I need the string.. potentially, it's not uber important, but I may as well. My question is, how do I read bytes until the byte is a null character?

Thanks again in advance,

Nathan
0

Share this post


Link to post
Share on other sites
[quote name='mynameisnafe' timestamp='1355088808' post='5008888']
My question is, how do I read bytes until the byte is a null character?
[/quote]

[code]
std::string s;
std::getline(the_stream, s, '\0');
[/code]
0

Share this post


Link to post
Share on other sites
Hi there,

I fixed it with this:

[CODE]
static std::string ReadString( int pos )
{
std::string ret;
int count = 0;
char val = ' ';
inputStream.seekg( pos, std::ios::beg );
while( val != '\0' )
{
ReadChunkPart( inputStream, val );
ret.append( 1, val );
count++;
}
current_pointer_position = inputStream.tellg();
return ret;
}
[/CODE]

I'm doing pretty well actually. I've chewed through the files chunks and found the data I need, and I've figured that way of getting strings.

The only question left for me to ask I think is this:

Given this template function, which reads the value of a type into a given instance of said type..

[CODE]
template<class T>
istream& read_binary( istream& in, T& val ) {
in.read( (char*)&val, sizeof(val) );
return in;
}
[/CODE]

How do I modify it to read in a given amount of a type into an array of said type? Something like below?

[CODE]
template<class T>
T * read_binary_array( istream& in, int count ) {

T * tmp = new T[ count ];

in.read( (char*) &tmp, count * sizeof(T) );

return tmp;

}
[/CODE]

Thanks again, you guys have been great! :)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0