How to Delete a file using remove() Function in C Program?

Delete a File Using remove() in C

A simple C program that deletes a file using the remove() function from <stdio.h>. It prompts the user for a filename and reports success or failure.

#include <stdio.h>

int main() {
   char filename[100];

   printf("Enter the file name to delete: ");
   scanf("%s", filename);

   if (remove(filename) == 0) {
       printf("File %s deleted successfully. ", filename);
   } else {
       perror("Error deleting file");
   }

   return 0;
}

How It Works?

  1. #include <stdio.h> — Provides remove() and perror().
  2. char filename[100]; — Buffer to store the filename entered by the user.
  3. scanf("%s", filename); — Reads the filename (no spaces).
  4. remove(filename) — Deletes the file. It returns 0 on success and a non-zero value on failure.
  5. perror("Error deleting file") — Prints the system error message if deletion fails (e.g., file not found or permission denied).

Example Run:

Enter the file name to delete: test.txt File notest.txt deleted successfully.

Note: The remove() function deletes files but cannot remove non empty directories. To delete directories, use rmdir() (POSIX). Always confirm with the user before deleting files in real programs.

7 Views