outputfile undeclared.

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 */
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
Code tags, please:
1
2
3
4
5
6
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 */

Although one can write single statement after if/else/while/for, it is safer to always use braces.
1
2
3
4
if (append)
{
  ofstream output_file(fname.c_str(), ios::app | ios::binary);
}

In this version it is absolutely clear that the output_file has a local scope, and thus is not visible later.

1
2
auto flag = (append) ? ios::app | ios::binary : ios::binary;
ofstream output_file(fname.c_str(), flag);
Topic archived. No new replies allowed.