Why does std::remove for file always return -1?

mato

I am trying to remove a file if exists. So first I test if the file exists and if it does I remove it using std::remove. test.json contains some json related txt in it. I also have #include <cstdio> included.

   std::string file_to_remove = "test.json";
   std::ifstream f(file_to_remove.c_str());

  if (f.good()) {
    int val = std::remove(file_to_remove.c_str());
    std::cout << "\nRemoving file : " << file_to_remove  << " : ret val : " << val<< std::endl;
  }

I was expecting the ret val to be 0 but I am getting -1

My current output is :

Removing file : test.json : ret val : -1

I have also made sure the file is closed.

Chipster

From the documentation of std::remove() (emphasis mine):

​If the file is currently open by this or another process, the behavior of this function is implementation-defined (in particular, POSIX systems unlink the file name although the file system space is not reclaimed until the last running process closes the file; Windows does not allow the file to be deleted).

Meaning if the file is open, it will not remove the file if you are on Windows. It will return an error (e.g. -1).

Any other platform could really be anything since it is implementation defined. I'd research your platform/compiler and see what the result of calling std::remove() on an open file is.

After adding f.close(); before std::remove ret val now is 0

That makes a lot of sense, since f.close() closes the file. The file is now closed, it it can be removed.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related