Finding file size with file input/output operations

Hey people,

I want to be able to find file size using file input/output operations "open()" function.

Typically, to open a file, we use for example: ifstream f ("/home/arjun/test_file.txt");

But, I want the complete file name ("/home/arjun/test_file.txt") to be stored in a variable so that any file can be opened and read from. I can then use other file handling operations to find its size.

Right now, if I am using a string variable to store the file name and then use it in the "open()" function, it's giving me errors.
Can it be done? If yes, how?

Thanks
Upgrade your compiler or use the c_str() member function to get a C-string from a std::string.
1
2
std::string filename = "/home/arjun/test_file.txt";
std::ifstream f(filename.c_str());
Thanks a lot Peter for your help. I tried out using c_str() function mentioned by you and it works.
What has upgrading my computer got to do with this? My machine is a recent product and is not old though.

Upgrading your compiler, not your computer - as in, the thing you build your program with. If you are using Code::Blocks or GCC or Clang or something along those lines, your compiler could well be recent enough, you just need to pass -std=c++11 to the command line (or find the option for C++11 compliance in the build settings). This is because before C++11, std::fstream did not have a constructor taking a std::string, only a const char*.
Last edited on
Hey NT3, my bad for misreading compiler. Thanks for this new option for 'g++'. It worked!
Finding file size with file input/output operations
Don't. Check the file's metadata instead.

Opening a file is among one of the most expensive things you can ask an OS to do, so don't do it lightly.
Topic archived. No new replies allowed.