The remove function in C/C++ can be used to delete a file. The function returns 0 if files is deleted successfully, other returns a non-zero value.
#include<stdio.h> int main() { if (remove("abc.txt") == 0) printf("Deleted successfully"); else printf("Unable to delete the file"); return 0; } |
Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed.
Explanation: This can be done using the remove function in C. Note that, this is done in Linux environment. So, the remove function is fed the first parameter in command line argument i.e. a.out file (executable file) created after compiling . Hence the program will be destroyed.
#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
After the output shown above, the a.out file will be removed.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Program to delete a line given the line number from a file
- C program to copy contents of one file to another file
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C Program to count number of lines in a file
- C Program to print contents of file
- C Program to merge contents of two files into a third file
- C++ program to print unique words in a file
- C Program for Lower Case to Uppercase and vice-versa in a file
- C++ program to read file word by word
- C++ program to append content of one text file to another
- LEX program to add line numbers to a given file
- C Program to find size of a File
- Lex program to take input from file and remove multiple spaces, lines and tabs
- C++ program to create a file
- C Program to count the Number of Characters in a File
- C program to print odd line contents of a File followed by even line content
- delete and free() in C++
- "delete this" in C++
- C++ | new and delete | Question 2
- C++ | new and delete | Question 3

