C++ Program to Delete a File

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

Things to Do Before the Program

Before starting the program, delete a file, say, codescracker.txt, using C++ code from the current directory. A file called 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 write a C++ program that deletes the file named codescracker.txt.

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

Delete a File from the Current Directory

To delete any file from the current directory using the C++ programming language, you have to ask the user to enter the name of the 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 the file as its argument and returns 0 if the file gets deleted successfully. And if it doesn't return 0, something strange happened, such as a missing file or the user not having 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:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    intstatus;
    char fileName[20];
    cout<<"Enter the Name of File: ";
    cin>>fileName;
    status = remove(fileName);
    if(status==0)
        cout<<"\nFile Deleted Successfully!";
    else
        cout<<"\nError Occurred!";
    cout<<endl;
    return 0;
}

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

C++ program to delete files

Now enter the name of the 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 open the folder "cpp programs" (the folder where you've saved the file codescracker.txt and above source code), it looks like the snapshot given below. That is, the file gets removed from this folder:

c++ delete file

The same program in different languages

C++ Quiz


« Previous Program Next Program »


Liked this post? Share it!