C Library - remove() function



The C library remove(const char *filename) function deletes the given filename so that it is no longer accessible.

Syntax

Following is the C library syntax of the remove() function −

remove(const char *filename);

Parameters

This function takes only a single parameter −

  • filename: This is a pointer to a string that specifies the name of the file to be deleted. The filename can include a relative or absolute path.

Return Value

The function returns 0 if the file is successfully deleted.It returns a non-zero value if an error occurs. In case of an error, errno is set to indicate the specific error code, which can be used to determine the cause of the failure.

Common Error codes

  • ENOENT: The file specified by filename does not exist.
  • EACCES: Permission denied to delete the file.
  • EPERM: The operation is not permitted, for instance, trying to delete a directory.

Example 1: Successfully Deleting a File

This example creates a file named example1.txt and then successfully deletes it using the remove function.

Below is the illustration of the C library remove() function.

#include <stdio.h>

int main() {
   const char *filename = "example1.txt";
   
   // Create a file to be deleted
   FILE *file = fopen(filename, "w");
   if (file) {
       fprintf(file, "This is a test file.\n");
       fclose(file);
   }

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

   return 0;
}

Output

The above code produces following result−

File example1.txt successfully deleted.

Example 2: Deleting a File Without Permission

This example simulates attempting to delete a file without the necessary permissions, resulting in a permission denied error.

#include <stdio.h>
#include <errno.h>

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

   // Create a file to be deleted
   FILE *file = fopen(filename, "w");
   if (file) {
       fprintf(file, "This is a test file with restricted permissions.\n");
       fclose(file);
   }

   // Simulate restricted permissions (actual permission setting code omitted for simplicity)

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

   return 0;
}

Output

After execution of above code, we get the following result

Error deleting file: Permission denied
Advertisements