C++ program to delete a file

C++ program to delete a file:

In this post, we will learn how to delete a file in C++. C++ provides one method called remove that can be used to delete a file. For deleting a file, we need the path of the file. If it can remove the file successfully, it returns 0 if the deleteing is successfull. For this program, we will remove one file that is in the current directory.

C++ program:

Here is the complete program:

#include <iostream>

using namespace std;

int main()
{
    char fileName[] = "hello.txt";

    cout << "Deleting file " << fileName << endl;

    int result = remove(fileName);

    if (result == 0)
    {
        cout << "File is deleted\n"
             << endl;
    }
    else
    {
        cout << "Unable to delete.\n"
             << endl;
    }
}

Explanation:

Here, we are deleting a file hello.txt that is in the same folder as the program file. If it exists, this program will delete that file using remove and shows the message that the file is deleted. Else, it will show one message that it is unable to delete it.

We are printing the message based on the return value of remove.

You might also like: