How to know the length of a file before reading it?

Its possible to know the length of a .txt file before reading it?

I always do the following:
1
2
3
char text[500000] = ".";
fread(text, sizeof(char)||sizeof(int), 500000-1, filepad);
textLength = strlen(text);


Thanks!
> Its possible to know the length of a .txt file before reading it?

If the file is not too big, and if you have to read all of it it anyway, change the sequence of operations. Read the file first:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
#include <fstream>
#include <iterator>

std::string read_text( const char* path2file )
{
    std::ifstream file( path2file ) ;
    return std::string( std::istreambuf_iterator<char>(file),
                        std::istreambuf_iterator<char>() ) ;
}

int main()
{
    std::string text = read_text( "myfile.txt" ) ;
    auto text_length = text.size() ;
}
You want to use std::ifstream.tellg(). It returns the number of characters from the beginning to the file pointer. To set the position of the file pointer, you want to use std::ifstream.seekg(ios::end). This moves the pointer to the end of the file.
Topic archived. No new replies allowed.