C Program to Delete a File Using remove() — Safe Code with Error Handling

The remove() function in C deletes a file from the filesystem. Defined in <stdio.h>, it works on both Windows and Linux — making it the standard, portable way to delete files from a C program.

Syntax

int remove(const char *filename);

filename is the path to the file — relative to the working directory (e.g. data.txt) or absolute (e.g. /tmp/data.txt on Linux, C:\temp\data.txt on Windows).

Return value: 0 on success, non-zero on failure. When it fails, the global variable errno is set to indicate the reason.

Example 1 — Delete a File (Hardcoded Path)

#include <stdio.h>

int main(void)
{
    const char *filename = "test.txt";

    if (remove(filename) == 0)
        printf("Deleted: %s\n", filename);
    else
        perror("Error");

    return 0;
}

perror() prints the system error message automatically. Instead of a vague “Error deleting file”, you get the actual reason — for example: Error: No such file or directory.

Example 2 — Delete a File Entered by the User

#include <stdio.h>
#include <string.h>

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

    printf("Enter file path to delete: ");
    if (fgets(filename, sizeof(filename), stdin) == NULL) {
        fprintf(stderr, "Input error\n");
        return 1;
    }

    /* Strip the trailing newline that fgets leaves in */
    filename[strcspn(filename, "\n")] = '\0';

    if (remove(filename) == 0)
        printf("Deleted: %s\n", filename);
    else
        perror(filename);

    return 0;
}

Why fgets() and Not gets()?

gets() was removed from the C standard in C11 because it has no bounds checking — a long filename silently overflows the buffer and corrupts memory. fgets(filename, sizeof(filename), stdin) reads at most sizeof(filename) - 1 characters, so the buffer is always safe regardless of input length.

Sample Output

Success

Enter file path to delete: /tmp/test.txt
Deleted: /tmp/test.txt

File does not exist

Enter file path to delete: /tmp/missing.txt
/tmp/missing.txt: No such file or directory

Permission denied

Enter file path to delete: /etc/hosts
/etc/hosts: Permission denied

Common errno Values When remove() Fails

errno value Meaning Common cause
ENOENT No such file or directory Wrong path or file never existed
EACCES Permission denied File is read-only or owned by another user
EISDIR Is a directory Path points to a directory — use rmdir() instead
EBUSY Device or resource busy File open by another process (Windows)

Bonus: rename() — Move or Rename a File

rename() is declared in the same <stdio.h> header. It moves or renames a file atomically (on the same filesystem):

#include <stdio.h>

int main(void)
{
    if (rename("old_name.txt", "new_name.txt") == 0)
        printf("File renamed successfully\n");
    else
        perror("rename");

    return 0;
}

Like remove(), it returns 0 on success and sets errno on failure. The atomic rename is useful for safe file replacement — write to a temp file, then rename over the target, so readers always see either the old file or the new one, never a partial write.

Key Points

  • Both remove() and rename() are in <stdio.h> — no extra headers needed
  • Always check the return value and call perror() when it fails
  • Use fgets() to read filenames from the user — gets() is unsafe and removed in C11
  • remove() only deletes files, not directories — use rmdir() for empty directories
  • Relative paths are resolved from the process’s current working directory, not the source file’s location

Related File Programs in C


As an Amazon Associate we earn from qualifying purchases.

Further Reading

The definitive reference for C — The C Programming Language by Brian Kernighan and Dennis Ritchie. Covers every concept on this site: pointers, arrays, structs, file I/O, and the standard library. Worth having on your desk.

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>