Open In App

How to Delete a File in C++?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
1 Like
Like
Report

C++ file handling allows us to manipulate external files from our C++ program. We can create, remove, and update files using file handling. In this article, we will learn how to remove a file in C++.

Delete a File in C++ 

To remove a file in C++, we can use the remove() function defined inside the <stdio.h> header file. The remove() function takes the path of the file as a string argument and deletes the file.

Syntax of remove()

remove(char * path)

where the path is the relative or even absolute path to the file.

If the function returns zero, the file has been successfully deleted. If the function returns a non-zero value, an error occurs.

C++ Program to Remove a File

The below example demonstrates how we can remove a file named “myfile.txt” in C++.


Output

File successfully deleted

Time Complexity: O(1), as file removal is a constant time operation. 
Auxilliary Space: O(1)

Explanation: The above code attempts to delete the file named "myfile.txt". If file is removed successfully, it prints "File successfully deleted". Otherwise, it prints an error message.

Note: The remove() function will not delete a directory. To delete a directory, we need to use the rmdir() function. Also, always ensure that the file is not open in your program or another program before attempting to delete it.

 


Practice Tags :

Similar Reads