Question
std::filesystem::remove throws std::filesystem_error when file is locked
Rahul River
0 reputation · 31 May 2022, 16:59 UTC
47.1K views0
Problem Context
The standard specifies that std::filesystem::remove throws std::filesystem_error when the removal fails. For a non‑existent path the error code is error_code::not_found, but for a file that is locked by another process the error code is implementation‑defined. The exception message derives from error_code::message(), which is system‑dependent.
Goal
Develop a cross‑platform strategy for detecting a locked‑file removal failure that works reliably on Windows, POSIX, and other systems.
Constraints
- The C++ standard does not prescribe the numeric value or category for a locked‑file error.
- Different operating systems return distinct error codes (e.g., ERROR_SHARING_VIOLATION on Windows vs. EACCES/EAGAIN on POSIX).
- Code must remain portable and not rely on hard‑coded numeric values.
Unresolved Questions
- What is the most reliable way to identify a locked‑file error using std::error_code without hard‑coding platform‑specific values?
- Should a program rely on the error category (generic_category vs. system_category) to differentiate lock failures, and if so, how can it be implemented portably?
- Is there a recommended pattern in the standard library or community to handle file‑lock errors that can be adopted as a best practice?