C

How To Delete a File in C

In this tutorial, we are going to see how to delete a file in C whose name will be entered by a user, the file to be deleted must be present in the directory where this program is located. The file extension must also be specified, the remove() function is used to delete a file. If there is an error in deleting the file, the error will be displayed by the perror function.
 

How To Delete a File in C
#include <stdio.h>

int main()
{
  char file[30];
    
  printf("Enter the name of the file you want to delete: ");
  gets(file);
    
  if (remove(file) == 0){
    printf("The file %s has been successfully deleted.\n",file);
  }    
  else
  {    
    printf("Cannot delete the file\n");
    perror("Error");    
  }
  return 0;
}

Output:

Enter the name of the file you want to delete: file.txt
The file file.txt has been successfully deleted.

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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