Overwrite existing file


#1

The doc at File::createOutputStream says:

Creates a stream to write to this file.

If the file exists, the stream that is returned will be positioned ready for
writing at the end of the file, so you might want to use deleteFile() first
to write to an empty file.

Actually I found that if I do so, I am sometimes receiving a nullptr when calling file.createOutputStream() directly after calling file.deleteFile() (tested on Windows 10).

However I can always get the stream and overwrite the existing file if I do this instead:

auto* stream = file.createOutputStream();
stream->setPosition(0);
stream->truncate();

Maybe the doc could tell this method instead and mention that this is more safe?


#2

That’s a good suggestion. I’ll update the docs.


#3

fyi your example has a leak…


#4

Ah yes, I was over-simplifying it… of course I need to delete stream, and should check for nullptr too:

std::unique_ptr<juce::FileOutputStream> stream(file.createOutputStream());
if(stream == nullptr)
{
    // The file can't be opened for some reason.
}
else
{
    stream->setPosition(0);
    stream->truncate();
    // Write to file
   // ...
}

#5

I think the example would have served most of the times. But simplest would be:

auto stream = std::make_unique<FileOutputStream> (file.createOutputStream());
if (stream)
{
    stream->setPosition(0);
    stream->truncate();
    // ...
}

#6

The best pattern to follow when writing this kind of thing is:

if (auto stream = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
{
    stream->setPosition(0);
    stream->truncate();
    // Write to file
   // ...
}