Hello,

I am trying to save elements into a file and it is not working. If the file is there, the new elements need to override everything in the file, pretty much clear it out and write to the file. If the file is not there, it just writes the elements to the file. I cant figure out why its not working. Thanks in advanced.
This is the section of where it is trying to save/create the file.

pfname = path + name + ".txt";
   ifl.open(pfname.c_str());
   if (!ifl) // --- THIS USER ID IS AVAILABLE
      ;
   else // --- THIS USER ID IS NOT AVAILABLE
      {
	  ifl.close();
      ofl.open(pfname.c_str());
      ofl << sz << graphName << endl; // --- EACH ITEM ON OWN LINE
      ofl.close();
      }
   ofl.open(pfname.c_str());
   ofl << graphName << '\n' << sz << '\n' << direct << '\n' << vert << '\n' << endl;
   ofl.close();

If the file is there, the new elements need to override everything in the file, pretty much clear it out and write to the file. If the file is not there, it just writes the elements to the file.

The default behavior when opening for writing is to truncate the file to zero length. When creating a new file, it's set to zero length. Thus, all you need to do is open the file for writing (whether it's there or not), and write to it. There doesn't need to be special logic depending on the presence or absence of the file.

The specific problem in your code is not knowing that opening a file for writing truncates it. Read your code with that in mind and the problem will stand out like a huge pimple. :D

The default behavior when opening for writing is to truncate the file to zero length. When creating a new file, it's set to zero length. Thus, all you need to do is open the file for writing (whether it's there or not), and write to it. There doesn't need to be special logic depending on the presence or absence of the file.

The specific problem in your code is not knowing that opening a file for writing truncates it. Read your code with that in mind and the problem will stand out like a huge pimple. :D

Got it! Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.