How can I get the length of a file in C++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I get the length of a file in C++?

Hi! How can I get the length of a file in C++? I have wrote this: long length(string filename) { long tor = 0; char c; ifstream von(filename); while(von.get(c)) tor++; return tor; } But it doesn't work if the file named filename is e.g. a picture (.png, .jpg, etc.) Can someone tell me why? Hope I will get some answers, S.A.

13th Sep 2020, 11:15 AM
Sebastian Ahlborn
Sebastian Ahlborn - avatar
1 Answer
+ 5
Sure you can iterate through a png. Even an exe, db and anything else. They are all just files with a bunch of characters in the end. But you have to open the file in binary mode to correctly read from them like: std::ifstream von( filename, std::ios_base::in | std::ios_base::binary ); If your compiler supports filesystem you can just use std::filesystem::file_size( path ) to get the file size. Another way you can do it is by simply ignoring everything in the file with file.ignore( std::numeric_limits<std::streamsize>::max() ); and then reading file's gcount with std::streamsize length = file.gcount(); ( You may need to include <limits> for this one ) But, this also requires the file to be opened in binary mode.
13th Sep 2020, 12:09 PM
Dennis
Dennis - avatar