How to know the length of a file before reading it?
Nov 15, 2012 at 6:55am UTC
Its possible to know the length of a .txt file before reading it?
I always do the following:
2 3 char text = ".";
fread(text, sizeof( char)|| sizeof( int), 500000-1, filepad);
textLength = strlen(text);
Nov 15, 2012 at 7:14am UTC
> 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:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <string>
std::string read_text( const char* path2file )
std::ifstream file( path2file ) ;
return std::string( std::istreambuf_iterator< char>(file),
std::istreambuf_iterator< char>() ) ;
std::string text = read_text( "myfile.txt" ) ;
auto text_length = text.size() ;
Nov 15, 2012 at 7:16am UTC
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.