Windows C++ : Delete a File

This post explains how to delete a file in windows using the function DeleteFileA() in C++.

Choose your favorite IDE with GCC compiler, Codeblocks or Microsoft Visual Studio are the preferred ones.

Create a new .cpp file, Let us call it deletefile.cpp.

The Header Files we use

  •         iostream.h
  •         windows.h

DeleteFileA()

DeleteFileA() is the function used to delete a file in windows.

Syntax

BOOL DeleteFileA( LPCSTR lpFileName );

BOOL is the return type of DeleteFileA() function.
If the file is successfully deleted the function returns a TRUE or else FALSE.
LPCSTR is the data type of the parameter passed to the function. lpFileName is the complete address of the path of the file to be deleted (along with the filename to be deleted).
 #include<iostream>  
 #include<windows.h>  
 using namespace std;  
 int main()  
 {  
   BOOL bDir;  
   LPCSTR lpFileName="Z:/New Folder/nob.txt";  
   bDir = DeleteFileA(lpFileName);  
   if(bDir)  
   {  
     cout<<"Successfully Deleted\n";  
   }  
   else  
   {  
     if(GetLastError()==ERROR_FILE_NOT_FOUND)  
     {  
       cout<<"Error: File Not Found\n";  
     }  
     else if(GetLastError()==ERROR_ACCESS_DENIED)  
     {  
       cout<<"Error: Access Denied\n";  
     }  
   }  
   system("PAUSE");  
 }  
Here nob.txt in Z drive inside New Folder is deleted. bDir gets a non zero value if DeleteFileA() succeeds or else will get zero.

IpFileName  variable is given address of the file to be deleted. You may have noticed that when you copy an address in Windows, By default we get Z:\ for Z drive, But in the program instead of backslash '\' frontslashes '/' are used. This is because '\' is a special character and to use it we should put '\\' for one \. But windows don't mind using frontslash '/' instead of '\' so it is used in the program.  

I hope you understood how DeleteDirectoryA() function works to delete a file. If you have any questions or doubts regarding this feel free to ask it by commenting below.

Note 

Deleting a file(.txt,.png,.pdf,etc) and deleting a directory or folder have different methods or functions in windows using C++. To delete a directory or folder use RemoveDirectoryA() function.

More Windows C++  

 
Windows C++ : Delete a File Windows C++ : Delete a File Reviewed by Jobin Jose on July 06, 2019 Rating: 5

No comments:

Powered by Blogger.