The Wayback Machine - https://web.archive.org/web/20241109103541/https://www.geeksforgeeks.org/c-program-delete-file/
Open In App

C program to delete a file

Last Updated : 06 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The remove() function in C/C++ can be used to delete a file. The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined inside the <stdio.h> header file.

Syntax of remove()

remove("filename");

Parameters

  • This function takes a string as a parameter, which represents the name of the file to be deleted.

Return Value

  • The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value.

Examples of remove()

Example 1:

The below C program demonstrates the use of remove() function.

C




// C program that demonstrates
// the use of remove() function
#include <stdio.h>
 
int main()
{
    if (remove("abc.txt") == 0)
        printf("Deleted successfully");
    else
        printf("Unable to delete the file");
 
    return 0;
}


Output

If file deleted successfully
Deleted successfully
            OR
If file not deleted successfully
Unable to delete the file

Example 2:

Using remove() function in C, we can write a program that can destroy itself after it is compiled and executed.

C




// C program that can destroyitself
//after it is compiled and executed
//using remove() function.
#include <stdio.h>
#include <stdlib.h>
 
int main(int c, char* argv[])
{
    printf("By the time you will compile me I will be "
           "destroyed \n");
 
    // array of pointers to command line arguments
    remove(argv[0]);
 
    // Note: argv[0] will contain the executable file i.e.
    // 'a.out'
 
    return 0;
}
 
// This code is contributed by MAZHAR IMAM KHAN.


Output

By the time you will compile me I will be destroyed

Explanation

Note that, this is done in the Linux environment. The remove function is fed the first parameter in the command line argument i.e. a.out file (executable file) created after compiling. Hence the program will be destroyed.

Note: After the output shown above, the a.out file will be removed.



Previous Article
Next Article

Similar Reads

C program to copy contents of one file to another file
[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) { printf("Cannot open fi
1 min read
LEX program to add line numbers to a given file
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Example: Input: #include<stdio.h> // Driver Code int
2 min read
C Program to count the Number of Characters in a File
Counting the number of characters is important because almost all the text boxes that rely on user input have certain limitations on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is
2 min read
C Program to count number of lines in a file
C/C++ Code /* C Program to count the Number of Lines in a Text File */ #include <stdio.h> #define MAX_FILE_NAME 100 int main() { FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be // either in current folder or complete p
1 min read
C Program to merge contents of two files into a third file
Let the given two files be file1.txt and file2.txt. The following are steps to merge. 1) Open file1.txt and file2.txt in read mode. 2) Open file3.txt in write mode. 3) Run a loop to one by one copy characters of file1.txt to file3.txt. 4) Run a loop to one by one copy characters of file2.txt to file3.txt. 5) Close all files. To successfully run the
2 min read
Write a C program that displays contents of a given file like 'more' utility in Linux
Write a C program that displays contents of given line page by page. Given number of lines to show as 'n' at a time and a file name, the program should first show n lines, then wait for user to hit a key before showing next n lines and so on. We strongly recommend to minimize the browser and try this yourself first. We can open the given file and p
2 min read
C++ program to print unique words in a file
Write a function that takes a file name as argument and prints all unique words in it. We strongly recommend you to minimize your browser and try this yourself first The idea is to use map in STL to keep track of words already occurred. C/C++ Code // C++ program to print unique words in a string #include <bits/stdc++.h> using namespace std; /
2 min read
C++ | new and delete | Question 2
Which of the following is true about new when compared with malloc. 1) new is an operator, malloc is a function 2) new calls constructor, malloc doesn't 3) new returns appropriate pointer, malloc returns void * and pointer needs to typecast to appropriate type. (A) 1 and 3 (B) 2 and 3 (C) 1 and 2 (D) All 1, 2 and 3 Answer: (D) Explanation: See mall
1 min read
C++ | new and delete | Question 3
Predict the output? #include <iostream> using namespace std; class Test { int x; Test() { x = 5;} }; int main() { Test *t = new Test; cout << t->x; } (A) Compiler Error (B) 5 (C) Garbage Value (D) 0 Answer: (A) Explanation: There is compiler error: Test::Test() is private. new makes call to the constructor. In class Test, constructor
1 min read
C++ | new and delete | Question 4
What happens when delete is used for a NULL pointer? int *ptr = NULL; delete ptr; (A) Compiler Error (B) Run-time Crash (C) No Effect Answer: (C) Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.Quiz of this Question
1 min read
C++ | new and delete | Question 5
Is it fine to call delete twice for a pointer? #include<iostream> using namespace std; int main() { int *ptr = new int; delete ptr; delete ptr; return 0; } (A) Yes (B) No Answer: (B) Explanation: It is undefined behavior to call delete twice on a pointer. Anything can happen, the program may crash or produce nothing. Quiz of this Question
1 min read
delete and free() in C++
delete and free() in C++ have similar functionalities but they are different. In C++, the delete operator should only be used for deallocating the memory allocated either using the new operator or for a NULL pointer, and free() should only be used for deallocating the memory allocated either using malloc(), calloc(), realloc() or for a NULL pointer
3 min read
"delete this" in C++
Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined. C/C++ Code class A { public: void fun() { del
1 min read
C | File Handling | Question 1
Which of the following true about FILE *fp (A) FILE is a keyword in C for representing files and fp is a variable of FILE type. (B) FILE is a structure and fp is a pointer to the structure of FILE type (C) FILE is a stream (D) FILE is a buffered stream Answer: (B) Explanation: fp is a pointer of FILE type and FILE is a structure that store followin
1 min read
C | File Handling | Question 2
When fopen() is not able to open a file, it returns (A) EOF (B) NULL (C) Runtime Error (D) Compiler Dependent Answer: (B) Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.Quiz of this Question
1 min read
C | File Handling | Question 3
getc() returns EOF when (A) End of files is reached (B) When getc() fails to read a character (C) Both of the above (D) None of the above Answer: (C) Explanation: See EOF, getc() and feof() in CQuiz of this Question
1 min read
C | File Handling | Question 4
In fopen(), the open mode "wx" is sometimes preferred "w" because. 1) Use of wx is more efficient. 2) If w is used, old contents of file are erased and a new empty file is created. When wx is used, fopen() returns NULL if file already exists. (A) Only 1 (B) Only 2 (C) Both 1 and 2 (D) Neither 1 nor 2 Answer: (B) Explanation: See https://www.geeksfo
1 min read
C | File Handling | Question 5
fseek() should be preferred over rewind() mainly because (A) rewind() doesn't work for empty files (B) rewind() may fail for large files (C) In rewind, there is no way to check if the operations completed successfully (D) All of the above Answer: (C) Explanation: Please see fseek() vs rewind() in CQuiz of this Question
1 min read
Difference between Header file and Library
Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extensi
3 min read
What is data type of FILE in C ?
Prerequisite : Basics of File Handling In C language, while file handling is done a word FILE is used. What is FILE? Example FILE *fp1, *fp2; While doing file handling we often use FILE for declaring the pointer in order to point to the file we want to read from or to write on. As we are declaring the pointer of type FILE so we can say it is data t
3 min read
LEX code to extract HTML tags from a file
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Approach: The extraction is based on the way tags are w
1 min read
Bank account system in C using File handling
This article focuses on how to create a bank account system using C language and File handling in C. Approach:Let's discuss the approach in detail, covering all the functions and their explanation in detail- Create a Menu in the main function and create different functions for the Menu, which will be called using switch case statements. There are f
12 min read
ATM using file handling in C++
In this article, the task is to implement an ATM with functions like add, delete, search, and update users using file handling in C++. File handling: File handling is used to store the output of a program in a file.In C++, files use three classes fstream, ifstream, ofstream available in fstream header file for file handling. Some Important Instruct
6 min read
cJSON - JSON File Write/Read/Modify in C
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language. JSON in C JSON in C can be handled using
6 min read
C File Pointer
A file pointer is a variable that is used to refer to an opened file in a C program. The file pointer is actually a structure that stores the file data such as the file name, its location, mode, and the current position in the file. It is used in almost all the file operations in C such as opening, closing, reading, writing, etc. SyntaxFILE *ptr; H
3 min read
fopen() for an existing file in write mode
In C, fopen() is used to open a file in different modes. To open a file in write mode, "w" is specified. When mode "w" is specified, it creates an empty file for output operations. What if the file already exists? If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the
2 min read
Comment in header file name?
What happens if there is a comment in header file name? Parsing of `#include' is slightly special because comments are not recognized within the ''. Thus, in `#include ' the `/*' does not start a comment and the directive specifies inclusion of a system header file named `x/*y'. Of course, a header file with such a name is unlikely to exist on Unix
1 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
Four File Handling Hacks which every C/C++ Programmer should know
We will discuss about four file hacks listed as below- Rename - Rename a file using C/C++Remove – Remove a file using C/C++File Size - Get the file size using C/C++Check existence – Check whether a file exists or not in C/C++ C/C++ Code // C++ Program to demonstrate the // four file hacks every C/C++ must know // Note that we are assuming that the
3 min read
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild
2 min read
Article Tags :
three90RightbarBannerImg