C Program to Delete a File

In this article, you will learn and get code about how to delete a file from the current directory using a C program. But before going through the program, we have to do a few things.

Things to do before the program

Before creating a C program to delete a file. Let's first create a file in the directory where the C source code is saved. Because I'm saving my source code file to a folder called "c programs" in my computer's Documents directory. Therefore, here is the snapshot of the folder, that contains a file named codescracker.txt

c delete file

You can also create a file in the directory where you are saving your C programs. Because after running the program, we have to enter the name of the file to be deleted. And at that point, I'll type the filename codescracker.txt. Now let's move on to the program.

Delete a File from the Current Directory

To delete a file, use a function namedĀ remove() that takes a string as a parameter. Here, the string parameter is the name of the file (with extension) that has to be deleted. This function returns 0 if the file is deleted. Here is the program that is used to delete any file present inside the current directory:

#include<stdio.h>
#include<conio.h>
int main()
{
    int status;
    char fname[20];
    printf("Enter FileName: ");
    gets(fname);
    status = remove(fname);
    if(status==0)
        printf("\nFile deleted successful!");
    else
        printf("\nUnable to delete file!");
    getch();
    return 0;
}

This program was built and runs under the Code::BlocksĀ IDE. Here is its sample run:

c program to delete files

Now type or enter the filename, say codescracker.txt, and press the ENTER key to delete it. Here is the sample run:

delete a file in c

Now if you want to see the snapshot after the operation, here is the snapshot of the current directory (snapshot of the "c programs" folder as created earlier):

c program delete file from directory

The same program in different languages

C Quiz


« Previous Program Next Program »


Liked this post? Share it!