Counting lines in an ASCII file

Tagged:

There is more than one way to count lines in an ASCII file.

This is sample code. Add error handling and adjust to your requirements as necessary.

&& #1
CREATE CURSOR test (C(1)) 
APPEND FROM (lcAsciiFileName) TYPE SDF
lnRecCount = _TALLY
USE IN temp
 
&& # 2. The line length cannot exceed 8192 bytes. Would return 1 for empty file
lnRecCount = 0
lnFH = FOPEN(lcAsciiFileName)
DO WHILE NOT FEOF(lnFH)
  = FGET(lnFH, 8192) 
  lnRecCount = lnRecCount + 1
ENDDO
 
&& # 3.  In pre-VFP 9.0 file must have 65,000 or less lines
lnRecCount = ALINES(laTemp, FILETOSTR(lcAsciiFileName))
RELEASE laTemp
 
&& # 4 
SET MEMOWIDTH TO 10000           && to prevent wordwrap
? MEMLINES(FILETOSTR(lcAsciiFileName))

You might consider:

#DEFINE CRLF   CHR(13)+CHR(10)
#DEFINE LF     CHR(10)
 
? OCCURS(CRLF,FILETOSTR("SomeFile.txt"))  && Std Win format
 
? OCCURS(LF,FILETOSTR("SomeFile.txt"))    && Unix format

Both should give the same answer. You would need to add 1 to the outcome to account for the last line which is not terminated with the CRLF or LF.

Occurs/ALINES with FileToStr would be very slow (if would work at all) for big files (more than 16MB).