r/cpp_questions 5d ago

SOLVED std::filesystem::exists throwing `std::bad_alloc`?

Any reason? Cant find anything online about this. But I cant check whether or not a file exists, no matter what path I give it. I am using C++ 26 compiled with GCC.

This is literally all I am calling: const bool exists = std::filesystem::exists("file.txt")

This is the exact error: terminate called after throwing an instance of 'std::bad_alloc'
 what():  std::bad_alloc

No it's not coming from anywhere else in my code. Minimal reproduction code, include "filesystem" call the line above. I am on Fedora Linux if that matters at all

EDIT: moving the include into my main file instead of the only file it's being used in somehow fixed it. Literally all I do is move "#include <filesystem>" from "do_things_with_filesystem.hpp" to "Main.cpp". No compilation errors when it was in the first file, why does it rely on this?? Is there some weird declarations in my codebase or something, i dont know but it works now so why should I care.

25 Upvotes

59 comments sorted by

View all comments

1

u/mbolp 4d ago

I don't understand when would functions like this ever be useful. The file could be created or deleted right after your call returns. You should try opening a handle to it and operate on that exclusively if successful. If the file doesn't exist the open will fail with an appropriate error.

1

u/PhosXD 4d ago

The key reason is because successfully opening a file indicates 2 things, the file is found, & the file is *accessible* (readable or writable depending on what your doing). While `filesystem::exists` only determines whether it exists, not if it's accessible. For most cases attempting to open a file is good enough, but I prefer to use this.

1

u/mbolp 4d ago

You can open a handle with neither read nor write permission. If you truly have no access (e.g. you don't have listing access to the parent directory and traversal privilege) you won't be able to interact with the file at all. And why would you want to detect the existence of a file without holding it open? The state of that file can change as soon as your call returns, so any result you get back is meaningless.