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
- Read the file name safely:
fgets()reads at mostsizeof filename - 1characters, so a long name can never overflow the buffer (the oldscanf("%s", ...)pattern could).strcspn(filename, "\n")finds the newlinefgets()keeps, and we overwrite it with'\0'. - Call
remove(filename): the C standard says it returns 0 on success and nonzero on failure. On POSIX systems it maps tounlink()for regular files. - Report failures with
perror(): on failure, the operating system records why inerrno.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 ofscanf("%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 — somy file.txtwould silently becomemy.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()vsprintf():perror()writes tostderrand appends the reason fromerrno. Error messages belong onstderrso 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 callremove()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 viaperror() - Check-and-act race conditions — why “test then delete” is worse than “delete then check the result”
stderrdiscipline — errors on the error stream, results onstdout
Related C Programs
- File Handling in C — Complete Guide — fopen, fread, fwrite, fseek and more
- Copy One File to Another in C — the companion operation, with the int-not-char EOF trap
- Find the Size of a File in C — fseek and ftell
- Count Characters in a File in C — a mini
wc
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.