0

I have 2 fstream objects called oldFile and newFile and I want to find the non-Null elements in oldFile and write them into newFile of a destructor. The name of the file would be exactly the same "file.txt" so I am essentially overwriting oldFile with newFile.

~Destructor(){
    T foo;
    fstream newFile;
    oldFile.open(fileName, ios::in | ios::out | ios::binary);
    oldFile.clear();
    while(!oldFile.eof()){
        foo.readFromFile(oldFile);
        if(!foo.isNull()){
            foo.writeToFile(newFile);
        }
    }
}

Where do I go from here? How do I name the newFile object to "file.txt" and make sure that the oldFile object is overwritten? Very basic file I/O, don't need anything too fancy.

Thomas V.
  • 71
  • 4
  • `oldFile.clear();` clears the status flags. At that point in the program the only thing that could be wrong is failure to open the file, something you ought to check for. `while(!oldFile.eof())` is a bug that'll probably end with reading past the end of the file. See [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) for details. – user4581301 Jan 27 '21 at 04:40
  • This code is not opening the new file before writing to it. And you can't use 2 streams to read and write to the same file at the same time. Write to a completely separate file, then close both streams, delete the old file, and rename the new file. – Remy Lebeau Jan 27 '21 at 04:47
  • your scenario is often solved with using a temporary file like `/tmp/my_lovely_file` ... – OrenIshShalom Jan 27 '21 at 05:19

0 Answers0