Method to delete a file using c++

Hello,

I am wondering if anyone can point me in the right direction of how to do this but I would like to delete a file using c++ ue4. The file will have become obselete and will no longer be used as it is being replaced. I have the filepath for the function to use and the file is in .png format.

I have found IPlatformfile::delete and IFilemanger:: delete but im not sure how to use them (gave it a go but didnt know how to initialise them). My other question would be is deleting the file safe and clean or is there a different method i use. If I have to I can try and overwrite the file but i dont think that is a good idea. Any help is appreciated!

Let me know if you havge any questions or need any more info
Thanks!

Here’s how I would do it:

Given that MyFile is an FString representing the full path to the file…


//Make sure the path I have is valid both in characters and in that the file path actually exists
if (FPaths::ValidatePath(MyFile) && FPaths::FileExists(MyFile))
{
     IFileManager& FileManager = IFileManager::Get();
     FileManager.Delete(*MyFile);
}

Hope this helps.

Thank you it works great but will crash if you have an invalid filename as your comment states.
so a small addition to prevent any crash would be :


//Make sure the path I have is valid both in characters and in that the file path actually exists
if(!MyFile.isEmpty())
{
    if (FPaths::ValidatePath(MyFile) && FPaths::FileExists(MyFile))
    {
        IFileManager& FileManager = IFileManager::Get(); FileManager.Delete(*MyFile);
    }
}

Once again thank you!

3 Likes