Search code examples
c++fstream

How to return index of item in .dat file?


How do I return the location of an item in a .dat file?

in the search() function I attempting to find an item in the fractions.dat file and return it to the user. However the function always returns -2 (the value that the variable being returned was initialized to originally).

The if statement executes, but it appears that file.read(...) isn't setting cur to anything.

#include <iostream>
#include <fstream>

using namespace std;

struct Fraction
{
    int num, den;
};

int search(fstream& file, Fraction* f);
int menu();
void proccessChoice(int i);
Fraction* readFrac();

Fraction* fracs[100];
int index;
string fileName = "fractions.dat";
fstream file(fileName,  ios::in | ios::out | ios::binary);

int main()
{
    if (!file)
    {
        cout << "Error opening file. Program aborting.\n";
        system("pause");
        exit(1);
    }
    int choice;
    do
    {
        choice = menu();
        proccessChoice(choice);
    } while(choice != 3);

    system("pause");
    return 0;
}


int menu()
{
    int c;
    cout << "1.Enter new fraction" << endl;
    cout << "2.Find fraction location" << endl;
    cout << "3.Quit" << endl;
    cin >> c;
    return c;
}

void proccessChoice(int i)
{
    switch(i)
    {
    case 1:
        {
            cout << "Please enter a fraction to be stored: ";
            fracs[index] = readFrac();
            file.write(reinterpret_cast<char*>(fracs[index]), sizeof(Fraction));
            /*cout << fracs[index]->num << "/" << fracs[index]->den ;*/
            index++;
        }
            break;
    case 2:
        {
            cout << "Please enter a fraction to find: ";
            Fraction* fToFind = readFrac();
            int i = search(file, fToFind);
            cout << "The fraction is at position: "<< i << endl;
        }
            break;
    }
}
int search(fstream& file, Fraction* f)
{
    Fraction* cur = new Fraction();
    int pos = -2;
    if (!file)
    {
        cout << "Error opening file. Program aborting.\n";
        system("pause");
        exit(1);
    }
    while(!file.eof())
    {
        file.read(reinterpret_cast<char *>(cur), sizeof(Fraction));
        if((cur->num == f->num) && (cur->den == f->den))
        {
            cout << "\nFrac found!" << cur->num << "/" << cur->num<<endl;
            pos = file.tellg();
            return pos;
        }
    }
    return pos;
}

Fraction* readFrac()
{
    Fraction* f = new Fraction();
    char slash;
    cin >> f->num >> slash >> f->den;
    return f;
}

Solution

  • You're not starting the search from the beginning of the file. You need:

    file.seekg( 0, std::ios::beg );
    

    Similarly I think you're not appending to the end when writing to the file.

    file.seekp( 0, std::ios::end );