Caduchon
Caduchon

Reputation: 5201

What guarantee do I have after is_regular_file?

Considering a boost::filesystem::path p, is it possible to have boost::filesystem::is_regular_file(p) == true and std::ifstream(p.c_str()).is_open() == false in the same time? If yes, in which kind of situation?

The context is the writing of an assert for a comparison function:

bool identical_files(const boost::filesystem::path& p1, const boost::filesystem::path& p2)
{
  assert(boost::filesystem::is_regular_file(p1));
  assert(boost::filesystem::is_regular_file(p2));
  std::ifstream f1(p1.c_str());
  assert(f1.is_open()); // IS THIS REDUNDANT ???
  std::ifstream f2(p2.c_str());
  assert(f2.is_open());
  // ...
  // ...
  // ...
}

Upvotes: 3

Views: 728

Answers (1)

inetknght
inetknght

Reputation: 4439

The only guarantee you have is that at the time of the call, the path was a regular file. Because the filesystem is implicitly a race condition, the call between boost::filesystem::is_regular_file(p1) and std::ifstream f1(p1.c_str()) may actually be referring to two different objects.

Consider the scenario:

  • Process 1 calls boost::filesystem::is_regular_file(p1), succeeds and determines it's a "normal" file
  • Process 2 deletes path pointed to by p1
  • Process 1 calls std::ifstream f1(p1.c_str()), and fails to open the file

Can you see the race condition here?

Upvotes: 5

Related Questions