In this tutorial you will learn about the C Program to Delete a File from computer and its application with practical example.
In this tutorial, we will learn to create c program to delete a file In C programming language. The file must exist in the directory where the executable file of this program is present.
Before starting with this tutorial we assume that you are best aware of the following C programming topics: C Pointers, C File Handling, C Strings and C Input Output.
Create required files to delete
Let’s first create files (inside the current project directory) as following:
- f1.txt – file to be deleted
The file must be saved in the folder where you are saving program file. Put the following content in corresponding file:
I'm inside f1.txt file
How to Delete Files from computer?
In this C program we will delete file (f1.txt) from computer. The remove macro is used to delete a file from computer. If there is any error on deleting the file, this will be displayed by perror function.
C Program to Delete Files From Computer
In this program we will delete one file from computer . We would first declared and initialized the required variables. Next, we would prompt user to input source file names(f1.txt) . Later in the program we will delete file (f1.txt) using the “remove” macro. The deleted file will not go to the recycle bin, so you would not be able to recover or restore it. In order to recover deleted files you need special recovery software.
printf("Enter name of a file you wish to delete\n");
status = remove(file_name);
if (status == 0)
printf("%s file deleted successfully.\n", file_name);
printf("Unable to delete the file\n");
perror("Following error occurred");
In the above program, we have first declared and initialized a set variables required in the program.
- status = status flag
- file_name= to hold first source file name
Now, user needs to provide the source file name. We will assign it to variable ‘file_name’. Next, we will try to delete file using remove() function. The remove() function will return 0 if file gets delete. We will assign return value to status variable, to check file deleted or not.