Sep 11, 2013 at 5:34am UTC
I get an error saying output_file undeclared, but if I comment out the if(append == 1) and else ofstream output_file(fname.c_str(), ios::binary);
it compiles. Is the compiler complaining that it might not get declared because it's in a if else?
int CD_Database::General_Save(int append)
{
if (append)
ofstream output_file(fname.c_str(), ios::app | ios::binary);
else
ofstream output_file(fname.c_str(), ios::binary);
/*error output_file undeclared */
if(output_file.is_open())
{
output_file.write(reinterpret_cast<char*>(&cdsvector[0]), cdsvector.size() * sizeof(CD_T));
if (output_file.bad())
return -1;
}
else
return -1;
output_file.close();
return 0;
} /* end Save_File */
Sep 11, 2013 at 5:51am UTC
That's right.
1 2 3 4 5 6 7 8
if (condition)
{
int a;
} // a goes out of scope here
else
{
int a;
} // a goes out of scope here
You could do a few things:
1.
ofstream output_file(fname.c_str(), (append ? (ios::app | ios::binary) : ios::binary));
2.
1 2 3 4 5 6 7 8
ios_base::openmode mode;
if (append)
mode = ios::binary | ios::app;
else
mode = ios::app;
ofstream output( fname.c_str() , mode);
3.
1 2 3 4 5 6
ofstream output; // Don't open it yet
if (append)
output.open(fname.c_str(), ios::binary | ios::app);
else
output.open(fname.c_str(), ios::binary);
Last edited on Sep 11, 2013 at 5:52am UTC