views:

150

answers:

5

when I try to open a file for reading in my console application i get this error message: "Unhandled exception at 0x1048766d (msvcp90d.dll) in homework1.exe: 0xC0000005: Access violation writing location 0x00000000." It works fine 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 
A: 

Try adding a "mode" to the call on open like:

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

Shaun
A: 

check if you have permission to open the file: both write, read permissions

vehomzzz
A: 

How do you guarantee that there is still place in the inventory when reading the files? The inventory is fixed size, a file is inherently not... Could it be, perhaps, that the inventory index points, eventually, after the array itself, causing an access violation?

It's up to the compiler and the runtime to choose if, and how to, react on an index out of bounds condition. Probably, when compiled in release mode, even VS2008 won't complain...

xtofl
I should have clarified, I know that the first file will never have more than 100 unique products
TheGNUGuy
+1  A: 

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

while( !fin.is_open() )
{
...
}
AraK
Thanks, AraK! Your solution worked.
TheGNUGuy
A: 

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

You can check line per line by pressing F10 and see where it crashes; that's the line you want to look at.

Chaoz