How to determine the size of a file??

Thanks to read this message. I want load the data from a file to a dynamic array.

I dont know how to determine the size of the file. I can post the code if you want.
1
2
3
4
5
6
inline std::ios::pos_type filesize( const char* location )
{
    std::ifstream fin( location, std::ios::binary );
    fin.seekg( 0, std::ios::end );
    return fin.tellg();
}


or (from stack overflow)

1
2
ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();
Last edited on
Why not use a vector and use the push_back() function to add elements to the vector until all data is stored and then use .size() function to determine the size of the vector
That will take longer because of:

1
2
Memory allocation
Function calls


The method mentioned above is the way I will do it because you don't need to declare any extra variables, there is only one or two function calls you do and it is fast.
It seems idiotic to open the file, check the size, close it, reopen it, and read it.


if you only care about the size http://www.cplusplus.com/forum/general/71333/#msg380507
On windows I think stat is implemented using GetFileAttributesEx, but even so I am not sure if it opens the file behind the scenes.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946.aspx
Last edited on
@ne555, you don't need to close the file in order to read it after you find the size. Consider this code:

1
2
3
4
5
6
string contents;
cin.seekg(0, ios::end);
contents.resize(cin.tellg());
cin.seekg(0, ios::beg);
cin.read(&contents[0], contents.size());
istringstream iss(contents);


The above code will read an entire file content into a string. The file needs to be redirected to the program
Last edited on
but you can't avoid to close it if you use your shadow fiend `filesize()' function

> cin.read(&contents[0], contents.size());
don't forget the '\0' terminator
edit: nvm, looks fine.
Last edited on
Topic archived. No new replies allowed.