Thread: File Input from structue???

  1. #1
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115

    File Input from structue???

    I have a quick question about inputting data. More specifically data that is of the fallowing struct
    Code:
    enum sex {male, female};
    
    struct data
    {
    	char name[30];
    	sex MF;
    	int age;
    	double weight;
    };
    Some one has asked me for some help with this but I cant seem to work out how to input the data from this file. if anyone wants to view the file. I have been told that its formatted as per the above structure.

    All of the input and output I have always uses was using the fallowing method.
    Code:
    FILE *input;  // declare a pointer of type FILE
    char buffer[400];  // a buufer array
    input=fopen("C:\\Sales.txt","r");  // opens file
    read(buffer,1,200,input);  // read 200 characters to buffer
    Is there someway to use the above method? Or is there an alternative?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Perhaps
    struct data student;
    fread( &student, sizeof student, 1, input );


    Though you will need to open the file with "rb" mode.

    You also need to know that reading a binary file in unportable in a large number of ways.
    - structure padding and alignment varies between compilers.
    - endian-ess and data type sizes vary from machine to machine.
    To counteract all these issues, you would have to read the file one byte at a time.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Location
    South Africa
    Posts
    20
    This will work. I don't know how to do it using c++ streams though. You have to open the file in binary mode and read a chunk of data the size of your structure. If you pass fread() a pointer to your structure it will populate your structure (assuming the file has the correct format).

    Code:
    int main(int argc, char *argv[])
    {
        FILE * sFile;
        struct data student[10];
        
        if (NULL == (sFile = fopen("student.data", "rb")))
        {
            cout << "Could not open file" << endl;
            system("PAUSE");
            return -1;
        }
        cout << "name\tsex\tage\tweight:" << endl;
        for (int i=0; i<10; i++)
        {
            fread(&student[i], sizeof(data), 1, sFile);
            cout << student[i].name << "\t";
            student[i].MF?(cout << "female\t"):(cout << "male\t");     
            cout << student[i].age << "\t" << student[i].weight << endl;
        }
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    kyle

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    A structure can be read by writing your own operator>> and operator<< functions that takes that structure as an argument (and a istream/ostream as well, of course).

    You can use >> and << inside the structure reading function, if that's what you want to do.

    Note that this will read/write data in text form (assuming you use the >>/<< operators), not in binary form like the fread/fwrite functions do - there are good and bad things about that.


    If you want to use binary form, use the fstream::read and fstream::write
    http://www.cplusplus.com/reference/i...ream/read.html
    http://www.cplusplus.com/reference/i...eam/write.html

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Sep 2007
    Location
    South Africa
    Posts
    20
    Thanks for the info. So heres the revised example which contains both the c method and the c++ file stream method:
    Code:
    #define USE_STREAMS
    
    enum sex {male, female};
    struct data
    {
    	char name[30];
    	sex MF;
    	int age;
    	double weight;
    };
    
    using namespace std;
    int main(int argc, char *argv[])
    {
        int length;
        struct data student[10];
        
        #ifdef USE_STREAMS
        ifstream isFile;
        isFile.open ("student.data", ios::binary );
    
        isFile.seekg (0, ios::beg);
        // read data 
        for (int i=0; i<10; i++)
        {            
            isFile.read ((char *)(&student[i]),sizeof(data));
        }
        isFile.close();
        cout << "name\tsex\tage\tweight:" << endl;
        for (int i=0; i<10; i++)
        {
            cout << student[i].name << "\t";
            student[i].MF?(cout << "female\t"):(cout << "male\t");     
            cout << student[i].age << "\t" << student[i].weight << endl;
        }
        #else
        FILE * sFile;
         
        if (NULL == (sFile = fopen("student.data", "rb")))
        {
            cout << "Could not open file" << endl;
            system("PAUSE");
            return -1;
        }
        cout << "name\tsex\tage\tweight:" << endl;
        for (int i=0; i<10; i++)
        {
            fread(&student[i], sizeof(data), 1, sFile);
            cout << student[i].name << "\t";
            student[i].MF?(cout << "female\t"):(cout << "male\t");     
            cout << student[i].age << "\t" << student[i].weight << endl;
        }
        #endif //USE_STREAMS
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    kyle

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    student[i].MF?(cout << "female\t"):(cout << "male\t");
    Seems to me that this would be simpler:
    Code:
    cout << (student[i].MF ? "female : "male") << '\t';
    Also note that you'd need to include <fstream> for the streams version and <cstdio> for the C version.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 02:20 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Totally confused on assigment using linked lists
    By Uchihanokonoha in forum C++ Programming
    Replies: 8
    Last Post: 01-05-2008, 04:49 PM
  4. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM