Reading from a File

I'm having problems reading data from a binary file. My current code for reading from the file is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
SalesDB::SalesDB (const char* fileName)
        {
        ifstream inFile;
        inFile.open (fileName, ios::in | ios::binary);
        if (!inFile)
                {
                cout << "Error - unable to open input file " << fileName << endl;
                }
        while (inFile)
                {
                inFile.read((char*)this, sizeof(SalesDB));
                }
        inFile.close();
        }


I was told to use inFile.read((char*)this, sizeof(SalesDB)); as the command line to read the data from the file except I can't seem to register any data from it. Is there another command line I could use to read information from a binary file instead of that?
Why do you have a while loop at line 9?
The code at line 11 should read the data for a single object from the stream into the current object. If it works at all, it will end up with the last object from the file.

If the binary file contains the data for more than one object, it would seem more appropriate to open the file separately, and then pass the stream by reference.

Maybe like this:
1
2
3
4
void fred::save(ofstream &os)
{
    os.write((char *) this, sizeof(fred));
}


1
2
3
4
void fred::load(ifstream &is)
{
    is.read((char *) this, sizeof(fred));
}
I made myself a little function in something a while ago (I say made myself, someone on here helped me with it and now it is returning)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//global variables
int length;
char* text;

void read(string arg){//arg = file to open and save to text
    ifstream ifile;
    ifile.open(arg.c_str(), ios::binary);
    if(ifile.is_open()){
        ifile.seekg(0, ios::end); //Set the files internal pointer to end of file
        int length = ifile.tellg(); //Set length to position of the files internal pointer
        ifile.seekg(0, ios::beg); //Reset Position of pointer to 0
        char* text = new char[length]; //Set length of char*[] to file length
        ifile.read(text, length); //Read File upto Length limit
        ifile.close();
    }
    else
    cout << "\nError Opening File To Read!\n";
    return;
}
Last edited on
Topic archived. No new replies allowed.