CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2004
    Posts
    8

    read Binary Data file onto class

    Hey guys,

    I 'm having problem reading data from a text file.

    Sample.dat contains

    M
    Bob
    Dude
    56
    F
    Carmen
    Sandiago
    33
    VP

    my code is suppose to read the .DAT file using ios::binary
    and feed the information into a class.

    example class...

    class personInfo
    {
    char firstname[20];
    char lastname[20];
    int age;
    char gender;
    }

    class femleInfo : public personInfo
    {
    char title[5];
    }


    acutally I have a polymorphic function that reads male info into a maleInfo Class and femaleInfo into a femaleInfo class.

    The problem is,how do I read both male and female info seperately and load the appropriate class? (they both have differnt number of data members)....

    I tried using seekg function and to move the pointer but I didnt really understand it,

    another problem Im having is, how to read the the data from file into my class ???

    I tried myDataFile.read(reinterpret_cast (&fObject),fObjSize);
    and I thought this would copy each data item from the text file into the class varibales???

    that doenst seem to be happening, am I missing something?
    Can someone pls help.

  2. #2
    Join Date
    Aug 2001
    Location
    Stockholm, Sweden
    Posts
    1,664
    Your input file doesn't look binary to me. It looks each items are stored row wise, in plain ascii.

    Read the file row by row (with getline or fgets).

    Your problem can be solved quite nicely with good OO design.

  3. #3
    Join Date
    May 1999
    Location
    Southern California
    Posts
    12,266
    You say "suppose to read the .DAT file using ios::binary". As j0nas has indicated, binary is not the best choice. If the reason why you are "supposed" to use binary is because this is homework or class assignmment or such, then say so, so we know why you are using binary instead of text.

    Apparently the sex is the first item (field) in the file for each object (person). So you can execute a different function based on the sex to read the remainder of the object. Would that not work?

    Another possibility might be to read the entire file into a buffer in one read. Then process the data in memory. However since you say you have tried using seekg, you might misunderstand how to efficiently read the data in memory also.

    Note that age in the structure is an "int" but it is text in the file, so you can't read the data directly into the structure from the file.
    "Signature":
    My web site is Simple Samples.
    C# Corner Editor

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured