C++ Program to Delete a File

« Previous Program Next Program »

In this article, you will learn and get code to delete a file from the current directory in C++. Here the current directory means, the directory where you are saving your C++ source code, or going to save your C++ source code that deletes file as given below.

Things to Do before Program

Before starting the program to delete a file say codescracker.txt using C++ code from the current directory. The file say codescracker.txt must be created. Therefore the file is created and saved inside the folder cpp programs where I'm going to save the source code (given below) to delete this file:

delete a file in c++

Now let's move on to create a C++ program that deletes this file named codescracker.txt.

Note - You can create and save this file to the folder where you'll save your program given below.

Delete a File from Current Directory

To delete any file from the current directory using C++ programming language, you have to ask from user to enter the name of file first. And then perform the operation of deleting it from the directory.

The function remove() is used to delete a file. It takes the name of file as its argument and returns 0 if file gets deleted successfully. And if it doesn't returns 0, then anything strange occurred such as file doesn't exist or user has not the permission to access the directory etc.

The question is, write a program in C++ that deletes a file from the current directory. Below is its answer:

// C++ Program to Delete a File

using namespace std;
int main()
    int status;
    char fileName[20];
    cout<<"Enter the Name of File: ";
    status = remove(fileName);
        cout<<"\nFile Deleted Successfully!";
        cout<<"\nErorr Occurred!";
    return 0;

This program was build and run under Code::Blocks IDE. Here is its sample run. The above program is saved in cpp programs folder, where the file, codescracker.txt was created earlier:

C++ program to delete files

Now enter the name of file say codescracker.txt (as created earlier) to delete it, as shown in the output given below:

delete file from current directory c++

Now if you opens the folder cpp programs (the folder where you've saved the file codescracker.txt and above source code), then it looks like, as shown in the snapshot given below. That is, the file gets removed from this folder:

c++ delete file

Same Program in Other Languages

« Previous Program Next Program »