I've just writen the codes to get the size of a log file:
ifstream fin("/var/log/logfile",ios::ate);
int size = fin.tellg();
But it looks like that fin's position pointer was not set correctly if anyone else were editing the logfile.That is,it looks like ios::ate was reset for sanity if the fin's file:/var/log/logfile had been edited since fin was initialized.Does it true?
And what I want to get is just the size of the logfile(maybe not the very size but exact is better),is there any suggestions?
When you open a file in a stream, it doesn't know about the external changes the file gets while open in your program.
If you want to get the size of the file in a specific moment, close and reopen the file so it can load the new data
try this, it may help.
sometimes opening the file in binary mode helps if it has some non-printable characters. use ios::binary also while opening the file.
Otherwise try locking the file first and then open it to get the exact length of file.
To Bazzy:
Thanks for your reply. Well, it likes *know* the external changes.Here is the test program:
test.cpp:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream fin("/var/log/logfile",ios::ate); // the /var/log/logfile 's size is more than 330M
int size = fin.tellg()/1024; // to get the size of KB
if( size > 204800 ) cout<<"Overflow"<<endl;
else cout<<"logfile size ok."<<endl;
return 0;
}
When I run the program alone, the output is:
330159
Overflow
But when I run it as soon as I save the changes on vi( by command 'w') after editing it,the output varies:
91080
logfile size ok.
Though the size on the first line is not always 91080,but it's usually less than 330159. so bewildering.