In this article, we will write a C program to delete a file from a given directory. The program takes the name or path of the file that is to be deleted as input from the user, searches if it exists in the given directory, and deletes it permanently.
If the file does not exist, it prompts the user and returns from the program.
Sample Input:
Enter the name or path of the file: myfile.txt
Sample Output:
File myfile.txt deleted successfully
To delete a given file from a directory in C programming language, you can use the remove() function provided by the std I/O library(<stdio.h>
).
The remove()
function takes a single parameter which is the name or path of the file that is to be deleted from the system.
If the file is successfully deleted, it returns zero, otherwise, it returns a non-zero value denoting that some error occurred during deletion of the file.
The remove()
function has the below syntax:
int remove(const char *filename);
So, to delete a file from your system, all you need to do is, call the remove()
function by passing the name or path of the file as an argument and check if it returns 0. If yes, the file is deleted successfully, otherwise not.
See implementation in the following program:
// C program to delete a file #include <stdio.h> int main(){ char filename[100]; int isDeleted; printf("Enter the name or path of the file: "); scanf("%s", &filename); // Delete the file isDeleted = remove(filename); if(isDeleted == 0){ printf("File %s deleted successfully", filename); } else{ printf("Unable to delete the file"); } return 0; }
Output:
Enter the name or path of the file: myfile.txt File myfile.txt deleted successfully Enter the name or path of the file: data/myfile.txt File data/myfile.txt deleted successfully Enter the name or path of the file: nofile.txt Unable to delete the file
Note: When using the remove()
function to delete a file from your system, it is important to note that the remove()
function does not move the file to the recycle bin, instead, it deletes the file permanently.
That’s all for this article. Thanks for reading!