Search code examples
c++ifstream

ifstream keeps read even though the file does not exists anymore


I'm facing a problem using std::ifstream to read a file. I have a zip file called "nice_folder.zip" (71.6MB) and the following code that reproduces the issue:

#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <unistd.h>

int main() {

  size_t read = 0;
  size_t f_size = std::filesystem::file_size("nice_folder.zip");
  std::shared_ptr<char[]> buffer{new char[4096]};
  std::ifstream file{"nice_folder.zip"};
  while (read < f_size) {
    size_t to_read = (f_size - read) > 4096 ? 4096 : (f_size - read);
    file.read(buffer.get(), to_read);
    sleep(2);
    std::cout << "read: " << std::to_string(to_read) << "\n";
  }
}

The problem is the following: after some read cycles I delete the file from the folder but it keeps reading it anyway. How is it possible ? How can I catch an error if an user delete a file while reading using ifstream ? I guess that ifstream takes the content of the file into memory before start reading but i'm not sure.


Solution

  • If you're doing this on e.g. linux, then the OS will not actually delete the file until you've closed all file handles to it. So it might seem like the file is deleted, but it's still stored somewhere on disk. See e.g. What happens internally when deleting an opened file in linux.

    So if you're trying to detect this file deletion to prevent wrong reads, then don't worry, the file won't actually be deleted.

    If you close the stream, and then try and open it again for that file, you'll get an error. But that also means you won't be able to read from it...