WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Binary Functions

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Count Number of Lines in a File and Extract Line #79

Keywords: 	 line count extract line

Question:

Is there a function that will return the number of lines in a text file?

I am doing this at the moment, but it takes a long time and is not elegant.

	File = FileOpen ("myfile.txt","Read")
	NumberOfLines = 0
	while @TRUE
		Quote = FileRead(File)
		If Quote == "*EOF*" Then Break
		NumberOfLines = NumberOfLines + 1
	EndWhile
	FileClose(File)
Thanks.

Answer:

You can count occurances of anything in the file - including lines. Read the entire section on binary buffers - MUCH faster. Seconds instead of minutes.
	FileName = ("C:\Temp\Example.txt")
	String1 = @CRLF ; number of lines
	String2 = ":" ; number of whatever
	String3 = "s" ; number of letter s's

	fs1 = FileSize(FileName)
	buffer1 = binaryalloc( fs1 )
	BinaryRead( buffer1,FileName )
	a = BinaryStrCnt( buffer1, 0, fs1 - 1, String1)
	b= BinaryStrCnt( buffer1, 0, fs1 - 1, String2)
	c= BinaryStrCnt( buffer1, 0, fs1 - 1, String3)
	BinaryFree( buffer1 )
	MsgLine = StrCat("String1 = ",a,@CRLF,"String2 = ",b,@CRLF,"String3 = ",c)
	Message( "Results", MsgLine )

Question (cont'd):

so now that I have the number of lines in a text file, is there a quick way to extract a particular line number without looping?

If there are 260 lines and I wish to extract line number 79, how would I do that?

Answer:

Here's some undebugged code....
FName = ("C:\Temp\Example.txt")
fSize=FileSize(FName)
bb=BinaryAlloc(fSize)
BinaryRead(bb,FName)


;Extract line 79
findline=79

;Step 1, locate the 79th CRLF  WILL NOT WORK FOR LINE 1
ptr=0
ptrprev=0
for xx=1 to findline
    ptrprev=ptr
    ptr=BinaryIndexEx(bb, ptr, @crlf, @fwdscan, @true)
    if ptr == -1
       Message("eeeek","File is not that big.")
       exit
    endif
next

;Step 2
;so now ptrprev points to the CRLF BEFORE the line and ptr points to the CRLF after

myline=BinaryPeekStr(bb,ptrprev+2,ptr-ptrprev-2)
Message("line %findline%",myline
BinaryFree(bb)

Article ID:   W14137
Filename:   Extract Line 79 from a File.txt
File Created: 1999:06:09:14:33:46
Last Updated: 1999:06:09:14:33:46