Overwrite existing file

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?

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

fyi your example has a leak…

1 Like

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
   // ...
}

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();
    // ...
}

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
   // ...
}
1 Like

Since it was linked to in discord, just want to mention, calling make_unique is completely wrong and won’t compile. The version where Jules silently corrected me, is the correct approach, declaring a std::unique_ptr and initialising it with the existing stream returned from createOutputStream.

I wonder what’s the reason, why createOutputStream wasn’t changed like many others to return a unique_ptr in the first place? I guess it’s coming soon…