Quick .dat question


OK, so I figured teh problem with my .dat files but I encountered another one. I am doing this:

ofstream file;

int noob=50;

file << noob << endl;

Just to make teh file (test program)
But now I want to access the variable "noob" from .dat file "file" in a different program. How do I do that? I want to use textout_ex() to display the "noob" variable from "file".


Just a heads up. On this site, dat files refer to datafiles created by the grabber.
What you have is a simple text file. Please don't call it a dat file. Also, make life simpler and don't use text files.



pfile = pack_fopen( "thingy.dat", "w" ); //, "wp" ); // if you want it packed

pack_iputl( long value, pfile );

pack_fclose( pfile );



pfile = pack_fopen( "thingy.dat", "r" ); //, "rp" ); // if you want it packed

long value = pack_igetl( pfile );

pack_fclose( pfile );

Johan Halmén

If you want to access variables from a file, you probably want to use config files. You can read/save variables from/to a config file. You have to rename the variables in the config file. Of course you can use same names as in your program, but that's not automatic.

Tobias Dammers

Or, in case you are familiar with XML, you might consider TinyXML (but then, if you're not familiar with XML, or it's just a few single variables you need to save / load, XML is way overkill of course).
Otherwise, go with DanielH's or Johan Halmén's solutions.

You can, of course, use C++ iostreams to do the same thing, but there are some caveats:
- The stream operators << and >> format everything to strings, so they are not your first choice for storing raw variables. Use the ostream::put() and ostream::write() functions to output binary data, and istream::get() and istream::read() for raw input. Here is some reading for you.
- When using raw output, you can only read / write chars and char arrays; this is so you can resolve endianness issues yourself. Allegro's packfile routines will do the job for you, but if you want to use iostreams, then you need to do the (de)serialization yourself. e.g.:

void put_long(ostream& out, int val) {
  out.put(val & 0xFF);
  out.put((val >> 8) & 0xFF);
  out.put((val >> 16) & 0xFF);
  out.put((val >> 24) & 0xFF);

int get_long(istream& in) {
    (long)in.get() |
    ((long)in.get() << 8) |
    ((long)in.get() << 16) |
    ((long)in.get() << 24);

Don't make the common mistake to just write raw memory:

fout.write((char*)(&my_struct), sizeof(my_struct));

Endianness and struct padding may break compatibility between platforms, compilers, or even builds.
- A file produced with this method is not human-readable, and doesn't contain any extra data you could use for error checking. This is OK for small files, or where performance is a key feature; otherwise, config files or XML provide better debugging possibilities.

Thread #590901. Printed from Allegro.cc