C++ remove()

The remove() function in C++ deletes a specified file. It is defined in the cstdio header file.

Example

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
  char filename[] = "program.cpp";

// remove the file "program.cpp" int result = remove(filename);
cout << result; return 0; } // Output: -1

remove() Syntax

The syntax of the remove() function is:

remove(const char* filename);

remove() Parameters

The remove() function takes the following parameter:

  • filename - pointer to the C-string containing the name of the file along with the path to delete

Note: Variables of the C++ string class cannot be used as parameters for remove().


remove() Return Value

The remove() function returns:

  • zero if the file is successfully deleted
  • non-zero if error occurs in deletion process

remove() Prototype

The prototype of remove() as defined in the cstdio header file is:

int remove(const char* filename);

Delete Opened Files with remove()

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

  • 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.
  • Windows - The file won't be allowed to be deleted if it remains open by any process.

Example: C++ remove()

#include <iostream>
#include <cstdio>

using namespace std;

int main() {
  char filename[] = "C:\\Users\\file.txt";
	
// deletes the file if it exists int result = remove(filename);
// check if file has been deleted successfully if (result != 0) { // print error message cerr << "File deletion failed"; } else { cout << "File deleted successfully"; } return 0; }

Output

File deletion failed
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges