Thread: A small question...

  1. #1
    Registered User
    Join Date
    Jun 2006
    Posts
    29

    Question A small question...

    I've been dealing with binary files and i was wondaring if there's a way to read data using only unKnown structs.
    I'm using that code to deal with binary files:
    Code:
    struct User{
    int a;
    }
    User IUser_data;
    User OUser_data;
    fstream username_file("admin.bin",ios::binary|ios::in|ios::out); 
    OUser.a=1320;
    	username_file.write((const char *)(&OUser_data),sizeof(User));	
    	username_file.close();
    	username_file.read(( char *)(&IUser_data),sizeof
    (User));
    cout<<IUser_data.a<<endl;
    if there's a way to load it like this:

    Code:
    struct User{
    }
    User IUser_data;
    fstream username_file("admin.bin",ios::binary|ios::in); 
    OUser.a=1320;
    username_file.read(( char *)(&IUser_data),sizeof(User));
    cout<<IUser_data.a<<endl;
    I'll be glad for any comment.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    what I would do is first write the size of the binary block as an binary int (or long) followed by the data, that way the reads always know the number of bytes written
    Code:
    unsigned long sz = sizeof(User);
    username_file.write((const char *)(&sz),sizeof(unsigned long));
    username_file.write((const char *)(&OUser_data),sizeof(User));
    //
    // read
    //
    struct User{
       unsigned long size;
       unsigned char* data;
    };
    
    User u;
    
    username_file.read((const char *)(&u.size),sizeof(unsigned long));
    u.data = new unsigned char[u.size]; // assuming this is a c++ program  
    username_file.write((const char *)(&u.data),u.size);
    That will get the binary blob into ram, from there you can typecast it into any structure you want, provided of course the blob does not contain pointers that point to other places in memory. If it does then those pointers will not be valid and will have to be reset.
    Last edited by Ancient Dragon; 06-14-2006 at 09:41 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  2. Hi all, I have a small question...
    By Pandora in forum Windows Programming
    Replies: 3
    Last Post: 03-16-2003, 06:21 AM
  3. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  4. A small Question
    By CodeJerk in forum C++ Programming
    Replies: 2
    Last Post: 11-20-2002, 09:08 AM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM