I’m running a windows c++ multithreaded app in which one instance/thread of the server class is appending to the file. Other threads run client instances which only load up the file upon
each client’s startup.
When I get to within 2k bytes of the end of loading the file I check to see if the file has changed
in size, so I know to update how many total bytes to read. Once in a while the file size
I get back is erroneously determined to be zero(0). I am using the stat call below for this. When zero is returned, then as a sanity check, I then call getFileSizeWithTellg() to see what it returns and it returns the expected non-zero value. A value that is the same or greater than the initial value.
I realize that the cast to unsigned int could be problematic, but the files are never
larger than 5 mgBytes.
What could be causing the stat() call to return a zero value, when the ..Tellg call doesn’t?
Thanks for any insight into this.
/
/ snippets from methods in different classes
//
// from client class
ifstream fileSeqIn
fileSeqIn.open(fName.c_str(), ios::in | ios::binary |ios::ate);
// to get initial size
size = fileSeqIn.tellg();
fileSeqIn.seekg(0, ios::beg);
// later to determine if the file has grown
struct stat filestatus;
unsigned int size;
if (stat(fName, &filestatus ) == 0) {
size = (unsigned int)filestatus.st_size;
}
//
unsigned int getFileSizeWithTellg(char *fname)
{
// get length of file
is.open (fname, ios::binary );
is.seekg (0, ios::end);
length = is.tellg();
is.close();
return(length);
}
//-----------------------------------------------------------------------------
// from server class
ofstream fileSeqOut;
fileSeqOut.open(fName.c_str(), ios::app | ios::out |ios::ate |ios::binary);
One significant difference:
statreturns the system’s view of the size of the file;tellgreturns a value dependend on the internal state of the stream. File bases streams are buffered, and the data may not be passed on to the system until you flush or close the file. Do you get the same difference if you precede the call tostatwith a flush of the stream?