Open In App

remove() in C

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, remove() is a standard library function is used to delete a file from the file system. It provides a simple way to manage files in the storage from a C program.

Example:

C
#include <stdio.h>

int main() {

    // Remove the file
	remove("gfg.txt")

    return 0;
}

Output
File deleted successfully.

Explanation: In this program, remove() function attempts to delete the file named "gfg.txt" from the current directory. If the file exists and permissions allow, it is deleted; otherwise, the operation fails.

This article covers the syntax, uses and common example of remove() function in C:

Syntax

remove() is a standard library function defined in <stdio.h> header file in C.

remove(filename)

Parameters:

  • filename: Name of the file to be deleted.

Return Values:

  • If deletion of file is successful, it returns 0.
  • If deletion fails, it returns a non-zero value.

This return value can be used to check whether the remove operation was successful or not.

Examples of remove()

The following examples demonstrate the use of remove() in C programs.

Delete Multiple Files

C
#include <stdio.h>

int main() {
  
    const char *fs[] = {"gfg1.txt", "gfg2.txt",
                        "gfg.txt"};
    int n = sizeof(fs)/sizeof(fs[0]);
    
    
    // Create files to delete
    for (int i = 0; i < n; i++) {
        FILE *f = fopen(fs[i], "w");
        fclose(f);
    }
    
    // Delete multiple files using remove() in for loop
    for (int i = 0; i < n; i++) {
        if (remove(fs[i]) == 0)
            printf("Deleted %s.\n", fs[i]);
        else
            printf("Failed to delete %s.\n", fs[i]);
    }

    return 0;
}

Output
Deleted gfg1.txt.
Deleted gfg2.txt.
Deleted gfg.txt.

Remove Old Files to Add Latest Data

The remove() function can be used to delete old files from the system ensuring the current file always contains latest data.

C
#include <stdio.h>

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

    // Check and remove existing file
    if (remove(filename) == 0)
        printf("Old file deleted.\n");
  	else
        printf("No existing file to delete.\n");

    // Create a new file
    FILE *fptr = fopen(filename, "w");
  
    // Check file exist or not
    if (fptr != NULL)
        printf("new file is created");
  
  	// writing logic here......
  
    fclose(fptr);
    return 0;
}

Output
No existing file to delete.
new file is created

Similar Reads