einpoklum
einpoklum

Reputation: 131373

Should I prefer using basic_istream::tellg() or filesystem::file_size()?

Suppose I have a std::filesystem::path, which I then open as an std::ifstream, and suppose that I want to determine its size (e.g. maybe I want to read the whole file).

Should I prefer calling

auto file_size = std::filesyste::file_size(my_path);

or rather, after opening it, calling

my_fstream.seekg(0, std::ios::end);
auto file_size my_stream.tellg();

?

Relevant considerations (thanks commenters):

Upvotes: 1

Views: 119

Answers (2)

anatolyg
anatolyg

Reputation: 28241

You should think why you need a file size at all. Do you want to estimate how much time your processing will take? Do you want to do sanity checking and warn the user that the file looks wrong? You don't need the "absolutely correct" number for these purposes. I can't imagine any situation where "more correct" is significantly better than "less correct".

If you want to consider other aspects: std::filesystem::file_size(my_path) should be faster, but less compatible (c++17). ifstream is inconvenient because it requires two statements, but not so much if your code reads the file right afterwards.

Regardless of race conditions, you can't guarantee that you have any particular number of bytes to read until you actually read them.

Upvotes: 1

Christian Stieber
Christian Stieber

Reputation: 12496

This is more of an opinion, but I generally prefer working with the actual file handle if I have one already -- so, I'd use the tellg version.

This eliminates problems where the path changes while you have the handle open. Unix-ish systems can still modify the file while you're reading it, but there isn't much you can do there.

Upvotes: 2

Related Questions