Delete a File in C – remove() with Error Handling

To delete a file in C, call the standard library function remove() from <stdio.h>: it takes the file name as a string and returns 0 on success. That one line is portable across Linux, macOS, and Windows — no operating-system headers needed. What separates a toy example from production-quality code is what happens when deletion fails: the file may not exist, the process may lack permission, or another program may hold the file open. This page shows the complete pattern — safe filename input with fgets(), the remove() call, and real error reporting with perror() — in tested, warning-free C89. One warning before you run it: remove() bypasses the recycle bin and trash entirely; the file is gone for good.

How It Works — Step by Step

  1. Read the file name safely: fgets() reads at most sizeof filename - 1 characters, so a long name can never overflow the buffer (the old scanf("%s", ...) pattern could). strcspn(filename, "\n") finds the newline fgets() keeps, and we overwrite it with '\0'.
  2. Call remove(filename): the C standard says it returns 0 on success and nonzero on failure. On POSIX systems it maps to unlink() for regular files.
  3. Report failures with perror(): on failure, the operating system records why in errno. perror() prints your message plus the human-readable reason — “No such file or directory”, “Permission denied” — for free. A bare “Unable to delete” message throws that information away.

C Program to Delete a File

/* Delete a file in C using remove()
 * Compile: gcc -ansi -Wall -Wextra delete_file.c -o delete_file */
#include <stdio.h>
#include <string.h>

int main(void)
{
    char filename[256];

    printf("Enter the file name to delete: ");
    if (fgets(filename, sizeof filename, stdin) == NULL) {
        fprintf(stderr, "No input given.\n");
        return 1;
    }
    filename[strcspn(filename, "\n")] = '\0';   /* strip newline */

    if (filename[0] == '\0') {
        fprintf(stderr, "Empty file name.\n");
        return 1;
    }

    if (remove(filename) == 0) {
        printf("'%s' deleted successfully.\n", filename);
    } else {
        perror("Could not delete the file");
        return 1;
    }
    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra delete_file.c -o delete_file
./delete_file

Compiles with zero warnings. On Windows (MinGW), the same code works unchanged; the executable is delete_file.exe.

Sample Input and Output

Test 1 — the file exists (we created notes.txt first):

Enter the file name to delete: notes.txt
'notes.txt' deleted successfully.

Test 2 — the file does not exist:

Enter the file name to delete: missing.txt
Could not delete the file: No such file or directory

Both outputs are real captured runs of the exact code above.

Code Explanation

  • Why fgets() instead of scanf("%s"): scanf("%s") writes past the end of the buffer if the input is too long (a classic overflow), and it stops at the first space — so my file.txt would silently become my. fgets() handles both correctly.
  • The return-value check is the whole point: remove() tells you whether it worked. Code that ignores the return value reports success even when the file is still there.
  • perror() vs printf(): perror() writes to stderr and appends the reason from errno. Error messages belong on stderr so they still appear when normal output is redirected to a file.
  • No existence pre-check: old tutorials fopen() the file first to “check it exists”, then delete it. That’s a race condition (the file can vanish between the check and the delete) and an extra syscall. Just call remove() and handle the error.
  • Permanent deletion: remove() unlinks the file at the filesystem level. Nothing goes to the recycle bin — there is no undo.

What This Program Teaches

  • Safe string input — the fgets() + strcspn() newline-strip idiom
  • Error handling with errno — letting the OS tell the user exactly what went wrong via perror()
  • Check-and-act race conditions — why “test then delete” is worse than “delete then check the result”
  • stderr discipline — errors on the error stream, results on stdout

Related C Programs

Test yourself: our free C Programming Quiz app for Android has 150+ questions with explanations for every answer — including a whole File I/O category.

Recommended Book

Chapter 7 of The C Programming Language by Kernighan & Ritchie covers the standard I/O library this program is built on. We’ve solved all of the book’s exercises. Also on Amazon.com.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>