r/cpp • • 6d ago

4 filesystem performance traps in the standard library · Mathieu Ropert

https://mropert.github.io/2026/11/24/filesystem_traps/

I've been optimizing startup times on my project lately. Some of it came down to file I/O and some bits of the standard library I consider to be potential traps. Here's a writeup.

75 Upvotes

39 comments sorted by

6

u/misuo 6d ago

Checking for file existence as the first thing is probably also used to avoid special error handling. Say the file operation fails, you will need to know whether it was due to the file not existing (thus perhaps pass through code as it was really not an error), or actually a file operation error that you most likely want to handle (report back, log, whatever).

But I agree that checking on file existence also introduce TOCTOU problems/vulnerabilities.

6

u/mropert 5d ago

As I mentioned in the article, file open system cal already handle file not found with ENOENT or equivalent. If you handle all values from open in one place you will get all error cases including file not found. If you check if it exists before you'll have to handle this case twice.

1

u/ericonr 4d ago

If you check if it exists before you'll have to handle this case twice.

To me, this is one of the most relevant parts. It's less code to be written to do it the right way!

-3

u/gimpwiz 6d ago

Yep. Tradeoff of code clarity, error clarity, convenience, and speed.

It is very easy to write, read, and report errors for:

if (file not exists) print error file not found;
if (file not readable) print error file permissions;
... check other conditions ...
open file;
if (file not good) print other errors;
do stuff with file;

Now the question from OP basically is, is it worth the performance tradeoff to do checks like this before opening a file? Is this code clear, legible, easy to understand and debug, full of good error reporting, to make tradeoffs even worth considering?

Do you instead do the file open and then check for all the errors? Is it clearer or as clear, etc?

If you run the code once I might suggest that the naive approach is more than adequate.

If you run the code and pay to overhead and then read a huge file, ie, the overhead is proportionally tiny, then I might also suggest it's fine.

If you're reading small files regularly then you pay real penalties.

12

u/UndefinedDefined 6d ago

It makes no sense - when you open a file, literally all of the checks above would happen at kernel level. If you want to open a file, just open a file and process a failure when it happens.

As mentioned above TOCTOU could be a big issue in some cases.

12

u/TTachyon 6d ago

The filesystem impl on Windows assumes that any (const) char* you pass to it is ANSI, which means it goes through the usual ANSI to WTF16 translation, which will result in broken paths on any system that uses anything but ASCII.

The "solution" is to use the char8_t*/std::u8string(_view) types when interacting with it, which basically no codebase uses natively, and people are against the change in general.

5

u/mropert 6d ago

Sadly for filesystem on Windows most paths are better off being wchar/utf16. std::filesystem::path already handles that natively (the underlying char type depends on platform and it's wide chars on Windows).
If you make your own abstractions usually you assume UTF8 and convert to wide char behind the scenes when talking to Windows APIs. This does imply allocations, but usually one temporary malloc for holding the converted path is negligible compared to the a file operation system call.

5

u/TTachyon 6d ago

Going wchar_t for a Windows app might be sensible, but this means you'll have to do conversions on all the other OSes, and waste memory because wchar_t is 4 bytes everywhere else.

For me std::filesystem is just an unusable API given this. At best I might try to make a PAL layer over it to make it reasonable.

The only way to make it work well is if you're targeting Windows 10+ where you can designate your whole process as ANSI=UTF8, but I can't do that myself.

2

u/Jardik2 4d ago

Windows paths need not be utf16 conforming. They may not convert cleanly to utf8, see wtf8. 

1

u/TTachyon 3d ago

Fortunately I don't care about such abominations.

6

u/LB-- Professional+Hobbyist 5d ago

Not anymore. Starting with Windows 10 you can add a manifest entry that turns all the -A APIs into UTF-8 APIs: https://learn.microsoft.com/en-us/windows/apps/design/globalizing/use-utf8-code-page

EDIT: Just saw your other comment about not being able to do that, unfortunate.

2

u/WoodyTheWorker 4d ago

The solution is to use TCHAR or wchar_t functions (_tfopen or _wfopen, for example).

0

u/ack_error 4d ago

The TCHAR type and functions are aliases for the char or wchar_t functions depending on whether UNICODE is set. There is no reason to use them anymore as Win9x is long dead and rarely does anyone actually write code that can successfully work both A/W. There is also no guarantee that UNICODE is set even on currently maintained Win32 projects.

2

u/WoodyTheWorker 4d ago

Unicode build has always been the way to go. For quite a few years, UNICODE has been a default when Visual Studio creates a new project.

When Windows 95/98/ME was still in use, Microsoft provided unicows.dll to allow use of W-functions on these platforms.

0

u/ack_error 4d ago

UNICODE has been a default when Visual Studio creates a new project.

Yes... when recent versions of Visual Studio create a new project. But there are projects that have been up-converted from quite old versions of VS before UNICODE became the default.

Additionally, creating Visual Studio project with CMake instead of VS will select MBCS by default, so plenty of new Win32 projects are still compiling without UNICODE.

When Windows 95/98/ME was still in use, Microsoft provided unicows.dll to allow use of W-functions on these platforms.

Sure... but unicows also made TCHAR obsolete. Unicows allowed a project to unconditionally use wide-string functions instead of code needing to dual-compile for narrow and wide. The _t functions were only of use if you weren't using Unicows.

IMO, there's simply no benefit to using TCHAR and the _t functions anymore. Typically, it simply means your code doesn't compile if UNICODE isn't set as expected. Just call fopen or _wfopen, or A/W functions, and this issue goes away.

1

u/WoodyTheWorker 3d ago

When you use Win32 functions without A/W qualifier, you use TCHAR-derived types for its arguments: LPTSTR, LPCTSTR, and _T() strings. LP in those is a Win16 heritage: Long Pointer.

2

u/ack_error 3d ago

Yes, but this is the same problem with the same solution. Call CreateFileA() or CreateFileW() directly based on the type of path string you have, and you avoid any dependency on TCHAR, UNICODE, and which function the CreateFile macro maps to. And, as a bonus, you don't have to worry about your code breaking because some library decided to #undef CreateFile in their header.

22

u/HommeMusical 6d ago

This is not a new thing. There’s a bug report open since 2020. I suspect the underlying issue might be older since MSVC guarantees ABI compatibility with objects built with VS2015. On my i7 10700 with an M.2 SSD, this makes reads 3 times slower for large files (I found it in my texture loader).

Ouch!

24

u/teerre 6d ago

But again as with the previous trap, how likely it is that we will get a file size and then not open it?

When you're trying to count file sizes?

1

u/ericonr 4d ago

I disagree with the article title, because I feel like people should be taught systems programming better (it's not a "trap" in the library). Query functions are useful if that's what you want, otherwise, always open the resource and then query its information, using your handle.

That said, I think your quote cuts out the bit of context where they do show they know the cases for only file size:

But again as with the previous trap, how likely it is that we will get a file size and then not open it? Because if we do, there’s a cheaper way.

They are saying that for most cases, people want to open a file, and this is what they should do.

24

u/azswcowboy 6d ago

These aren’t traps, they are things to be aware of in using the library. Removing the ‘exists( file )’ function because some coder might not realize file open is just as fast most of the time ignores the group that actually has this as a valid use case and doesn’t need to open the file. Maybe try this on a network mounted file system and see if there’s a difference? Maybe we should ask rust and python to remove this function as well?

> … Microsoft bug…I guess the only solution is to complain even more at Microsoft.

The library is open source submit a patch.

This is much ado about nothing.

5

u/donalmacc Game Developer 6d ago

From the article though,

Actually, it’s worse than pointless: it’s wrong. Because even if exists() returns true, the subsequent call might still fail because the file was removed in between the calls.

It’s a race condition, and IME it’s almost always wrong.

5

u/inco100 6d ago

Well, what if n opened file got dismounted while working with it? What if one just wants to know if a file is just over there, but does not want to read or modify its content? In the real world, there are countless scenarios, so we got to draw the line somewhere when we are designing.

1

u/donalmacc Game Developer 2d ago

If a file is dismounted while working with it, checking it exists won’t help you. If you read, modify and then write the file, you need to handle at an app level “what do I do if this file disappears while I’m using it”.

what if one just wants to know if a file is over there but does not want to read or modify its content

Then you’re not going to call anything on the file after you check if it exists, so that’s fine. But if you’re going to get the time it was last updated, then just stat it and handle the error that you get back from that.

0

u/inco100 17h ago

Thank you, but maybe you are replying to the wrong person. I asked questions to provoke thoughts about use cases, not really to seek answers.

4

u/azswcowboy 6d ago

Things can be deployed such that a race condition is basically impossible. Just because the author lacks enough imagination to see the valid use cases doesn’t mean they don’t exist.

4

u/ericonr 4d ago

There's no valid use case for checking if a file exists immediately before opening it. Opening the file can fail for numerous reasons (erased file, changed permissions, drive or network failure, memory allocation failure, etc), so you still need to handle all possible errors at the open site, and it's simpler to do it just once (and reliably).

Things can be deployed such that a race condition is basically impossible.

Why rely on basically impossible when you can do things right?

2

u/azswcowboy 4d ago

I didn’t say the application was going to open the file right away or at all. The lack of file existence may be enough information to change the application behavior without ever opening it.

0

u/donalmacc Game Developer 2d ago

Was going to open the file right away

This is exactly the problem. Say you have some code that checks if cache.bin exists, and if it does then you go off and do something else and expect the cache to be there later. That’s literally the race condition we’re talking about.

or at all

Then this is fine because we’re literally talking about whether it’s valid to call exists() before opening the file. I’d also suggest that the number of use cases for “does this file exist” without doing anything with the file are incredibly small, and as such any use case should be treated with suspicion.

1

u/azswcowboy 2d ago

> incredibly small

Not zero. Here’s an easy one - user edits a document and is making a reference to another file name - editor can flag the file reference doesn’t exist. Please go ask Claude for some others. You’ve spent a lot of time arguing about something that changes nothing: every file api in many languages supports this interface and will continue to.

2

u/UnusualPace679 3d ago edited 3d ago

Trap #1: std::filesystem::exists() is almost always redundant

Sometimes I do want to check if a file exists without doing anything with it. For example, looking for the .git file is a quick (and dirty) way to find the project root.

C++20 added std::map::contains which I dislike because it solves the wrong problem.

It solves a problem that you don't have (checking if an element exists without accessing the element), but nonetheless a valid problem.

1

u/donalmacc Game Developer 2d ago

Sometimes I do want to check if a file exists without doing anything with it

I agree with OP - more often than not the usages I see are checking if a file exists before opening it. Every use of exists should be treated with caution, and looking for .git won’t guarantee what you want. A worktree won’t have a .git folder and you will have multiple .git’s if you’re in a sub module. It’s “dirty” because it’s wrong.

You might decide that tradeoff is worth it, and that’s fine, but I’m going to flag it and make you justify it if I’m reviewing your code.

0

u/UnusualPace679 2d ago

A worktree won’t have a .git folder

In this case .git is a regular file. This is why I use exists and not is_directory.

and you will have multiple .git’s if you’re in a sub module.

This can be fixed by walking up the directory tree until no .git file can be found.

It’s “dirty” because it’s wrong.

There's no way that is quick and correct. The git dir must have a specific layout, and it's tricky to verify it. It's also worthless if you know the project isn't evil.

I mean, exists has a clear usage: to check if a file exists without touching it. If it's used incorrectly, it's not the function's fault.

-2

u/tialaramex 3d ago

For containers their argument is that C++ does not provide a better API.

With an Entry API there's a mechanism to say "Where's the entry for key 123456?" and what you get back is either the entry that actually exists, with key 123456 and the associated value - which you can then modify, or a slot where that would go if you created it, so you needn't do the work to find that entry twice. I think an entry API might have been proposed for the STL containers at some point but I do not have a P-series number for such a proposal just a vague memory.

2

u/UnusualPace679 2d ago edited 2d ago

If you want to create a new element if one doesn't exist already, there's operator[]. There's also try_emplace if you want to have more control on how to create the element.

If you don't want to create a new element, but just want to access the element if it's present, there's find (old) or lookup (C++29).

-7

u/sweetno 6d ago

You can avoid these and similar issues by not using the standard library.

-1

u/robstoon 5d ago

This isn't really file system performance traps in the standard library. This is file system performance traps on Windows.

0

u/Jardik2 5d ago

Larger trap is the UB that you cannot avoid if you factor in a user using his computer...