0

When I try to write a binary file using ofstream::open the failbit is getting set I am unable to write the file and the exception reason is "basic_ios::clear". This should be so simple but I can't figure out what I'm doing wrong.

string fname ("/home/tim/data/kv.bin");

file.exceptions (std::ofstream::failbit | std::ofstream::badbit );

try
{
    file.open (fname, ios::binary);
}
catch (std::ofstream::failure e)
{
    string error (e.what());
}

From an xterm I can touch the filename listed without a problem but whenever I try to create it programmatically it fails.

I tried this

FILE *fp;
if ((fp = fopen (fname, "w')) == NULL)
{
    int err = errno;
}

and it opened the file without a problem. I guess I could use the C file pointer to write my file but I would like to remain consistent using the C++ streams that I use in the rest of my code.

Is there anyway to figure out why ofstream::open is failing and how to fix it?

DesertBroncoFan
  • 65
  • 1
  • 12

1 Answers1

2

I figured it out. I had used the ofstream earlier in my function and didn't close it before trying to open it with a different filename.

Sorry everyone.

DesertBroncoFan
  • 65
  • 1
  • 12
  • Very helpful "already open". This is e.g. when you decide later to use the open() method, but the constructor still has the file argument and so does an implicit open – Sam Ginrich Jul 30 '22 at 17:00