Join our newsletter for the latest updates.

C++ remove()

The remove() function in C++ deletes a specified file.

remove() prototype

int remove(const char* filename);

The remove() function takes a single argument filename and returns an integer value. It deletes the file pointed by the parameter.

Incase the file to be deleted is opened by a process, the behaviour of remove() function is implementation-defined.

In POSIX systems, if the name was the last link to a file, but any processes still have the file open, the file will remain in existence until the last running process closes the file. In windows, the file won't be allowed to delete if it remains open by any process.

It is defined in <cstdio> header file.

remove() Parameters

filename: Pointer to the string containing the name of the file along with the path to delete.

remove() Return value

The remove() function returns:

  • Zero if the file is successfully deleted.
  • Non zero if error occurs.

Example: How remove() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
	char filename[] = "C:\\Users\\file.txt";
	/*	Deletes the file if exists */
	if (remove(filename) != 0)
		perror("File deletion failed");
		cout << "File deleted successfully";
	return 0;

When you run the program, the output will be:

If the file is deleted successfully:
File deleted successfully
If the file is not present:
File deletion failed: No such file or directory
Did you find this article helpful?