C ++ error while opening file

when i try to open the file for reading in my console application i get this error message: "Unhandled exception at 0x1048766d (msvcp90d.dll) in homework1.exe: 0xC0000005: write location of access violation 0x00000000". It works great when I compile and run the program on my macbook, but when I run it on my desktop using VS 2008, it gives me this error.

here is my code:

int main (void) {



    // Open 1st file (baseproduct.dat)
    ifstream fin;
    //fin.open (filename.c_str ());
    fin.open ("baseproduct.dat");

    int tries;
    tries = 0;
    while (fin.bad ())
    {
        if (tries> = 4)
        {
            cout> filename;
        fin.open (filename.c_str ());

        tries ++;

    }

    SodaPop inventory [100];

    // read file into array
    string strName;
    double dblPrice;
    int i;
    i = 0;
    fin >> strName;
    while (! fin.eof ())
    {
        inventory [i] .setName (strName);

        fin >> dblPrice;
        inventory [i] .setPrice (dblPrice);

        fin >> strName;
        i ++;
    }
    fin.close ();

    cout> filename;

    //fin.open (filename.c_str ());
    fin.open ("soldproduct.dat");

    tries = 0;
    while (fin.bad ())
    {
        if (tries> = 4)
        {
            cout> filename;
        fin.open (filename.c_str ());

        tries ++;

    }

    // read file into array
    i = 0;
    fin >> strName;
    while (! fin.eof ())
    {
        cout> dblPrice;
        inventory [i] .setPrice (dblPrice); * /

        fin >> strName;
        i ++;

        //1. search array for name
        // 2. get price (what should happen with it?)
        // 3. add # sold to quantity
    }
    fin.close ();
cout 
+2


source to share


5 answers


If you want to check if a file is open or not, don't use fin.bad()

instead:



while( !fin.is_open() )
{
...
}

      

+1


source


Try adding "mode" to the open call, for example:



http://www.cplusplus.com/reference/iostream/ifstream/open/

0


source


Make sure you have permission to open the file: read and write permissions.

0


source


How do you ensure there is still inventory space when reading files? Inventory is a fixed size, the file is not essentially ... Could it be possible that the index of the inventory points, after all, after the array itself, causing an access violation?

It is up to the compiler and runtime to choose whether and how to react to the state of the index out of bounds. Maybe when compiled in release mode even VS2008 won't complain ...

0


source


Try placing breakpoints in parts of your code when using VS2008.

You can test line to line by pressing F10 and see where it fails; what is the line you want to look at.

0


source







All Articles