Quickly read last line in text file
Keywords: Binary read last line file
Question:
One DOS application creates a report and saves it to a disk file. I want to read that file and take the TOTAL which is at the end of the report. If I read the file with "FileRead", I have to read record by record until the last record, but that takes to much time because the report is big (2 MB).Can you tell me another method to reach the end of file without reading the file record by record?
Answer:
I think the binary operations will give you the speed you are looking for.The code would look something like this....
file="C:\Temp\abc.txt" fsize=FileSize(file) buffer=BinaryAlloc(fsize) ;read file into binary buffer BinaryRead(buffer,file) endoffile=BinaryEODGet(buffer)-1 While 1 ;locate lines by getting pointers to @CRLFS beginptr=BinaryIndexEx(buffer,endoffile,@CRLF,@BACKSCAN,0) if beginptr != '-1' endptr=endoffile-beginptr+1 lastline=BinaryPeekStr(buffer,beginptr,endptr) if lastline=="" || lastline==@CRLF endoffile=endoffile-2 continue endif ;trim @CLRF off string lastline=strReplace(lastline,@CRLF,'') message("Last Line",lastline) break else message("CRLF Not Found"," Not a valid ascii file.") break endif endwhile BinaryFree(buffer) message("Last line retriever","Done")
Article ID: W14711Filename: Quickly read last line in text file.txt