I came across this problem in one of my test papers.
It says : Write a program that deletes itself( the exe file ) when run.
Here's my first attempt and it didn't work, so I added the error-checking code.
/* This program tries to delete itself */
#include <stdio.h>
#include <conio.h>
#include <errno.h>
int main( int argc, char *argv[] )
{
printf("This program will delete itself. Press a key to continue...");
getch();
if( remove( argv[0] )) // remove() returns non-zero on error
{
printf("\nSome error has occcurred. Couldn't delete file. Error :");
switch( errno )
{
case EACCES : printf("Permission denied");
break;
default : printf("Unknown error.");
}
}
else
printf("\nFile %s deleted", argv[0] );
getch();
return 0;
}
The output is always "Permission Denied". Is there any other way to write this program?