how to get the end of the file? ios::ate doesn't work well.

Hello all,

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?

Thanks in advance.
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
If some one else is editing the file you can seek to the end of the file manually after opening the file using seekg.

1
2
fin.seekg (0, ios::end);
streampos length = is.tellg();


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>
using namespace 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.
Last edited on
To writetonsharma:
Thank you for your suggestions.
I've tried that seekg-then-tellg, but got the same result.

And yes, what I do is lock the file first and then get the length, it works fine.

Well, as what I said at first, is there no other methods to get the file's size on the fly? TIA.
Topic archived. No new replies allowed.