Hello,
I am trying to read a log file which is written by another application.
Other application is running,and writing lines to log file time to time.
At the same time I supposed to read log file without lose and as soon as modification occurs.
Even I check if the error occurs when opening file,
I can not get the line written when open file error occurs.
But it can not get some lines of the log file.
Below you can find the function which I am using to accomplish this job.
Thanks a lot
p.s. : I can not modify the other application.
while(1) |
{ |
loopTry++; |
if(CFile::GetStatus(fileName,filestatus)) |
{ |
if(filestatus.m_size > lastSize) |
{ |
if ( !myFile.Open( fileName, CFile::shareDenyWrite | // |
CFile::modeRead , &fileException ) ) |
{ |
CString cs; cs.Format(_T("Can't open file %s, error = %u readTry = %d"), |
fileName, fileException.m_cause,readTry ); |
log(cs); |
|
} |
else//oku |
{ |
readTry++; |
char * rBuffer = ::new char[filestatus.m_size+1-cursorPos]; |
rBuffer[filestatus.m_size-cursorPos] = '\0'; |
|
//READ START |
myFile.LockRange(0,filestatus.m_size);// |
myFile.Seek(cursorPos, CFile::begin);//TODO: compare seek overhead with reading up to cursorPos |
myFile.Read(rBuffer,filestatus.m_size-cursorPos); |
myFile.UnlockRange(0,filestatus.m_size); |
myFile.Close(); |
//READ END |
lastSize = filestatus.m_size; |
//PROCESS START |
std::string str(rBuffer); |
int lineEndPos = 0; |
int localCursor = 0; |
for(;;) |
{ |
std::string line; |
|
|
int lastNewlineIndex = str.find("\r\n",lineEndPos+1); |
if(lastNewlineIndex == std::string::npos)//if there is no newline left |
{ |
break; |
} |
lineEndPos = lastNewlineIndex; |
line = str.substr(localCursor,lineEndPos-localCursor); |
ProcessLine(line,loopTry,readTry);// some func to process line read |
localCursor = lineEndPos + 2; |
cursorPos += localCursor; |
} |
//PROCESS END |
::delete [] rBuffer; |
} |
} |
else//file size is not changed. wait { |
Sleep(wait); |
} |
} |
else |
{ |
CString cs; cs.Format(_T("can not get status. looptry = %d"),loopTry ); |
log(cs); |
} |
} |