Counter for ReadLine in a TextFile

Hi group, I would like to count how many lines there are in a text file. This is the solution I found.

I don’t like having to use a helper variable for the strIN.ReadLine that advances in the text file.

Is there a better solution?

Dim strIN As TextInputStream 
strIN = TextInputStream.Open(PathMyFile)
Dim Counter as integer=0
Dim Util as string
While Not strIN.EndOfFile
  Counter=Counter+1
  Util=strIN.ReadLine
Wend
strIn.Close
MessageBox " They are " + Counter.ToString + " rows"

Maybe (untested) … read the lot, split on end of line, look at how many array elements you get…

Dim strIN As TextInputStream 
strIN = TextInputStream.Open(PathMyFile)
Dim Util as string =strIN.ReadAll
strIn.Close
dim rows() as string = split(util, endofline)
messagebox  "Probably " + format(rows.ubound)  + " rows, plus or minus 1"

It depends on the size of your file. If it’s small enough, you can read in the whole file and use Split (Jeff beat me to it).

Otherwise, you can read in chunks of, say, 16k, use Split on each chunk and keep a running count.

Yes, my file it’s small … max 20 rows.

Hi Jeff, return an error:
Type mismatch error. Expected TextLiteral, but got Int32
messagebox “Probably " + format(rows.ubound) + " rows, plus or minus 1”

Ok guys, i solved it like this:

Dim strIN As TextInputStream = TextInputStream.Open(PathMyFile)

''READ ALL FILE TXT
Dim AllTextFromFileRead as string
AllTextFromFileRead=strin.ReadAll

Dim words() As string
words = AllTextFromFileRead.Split(chr(13))

messagebox " They are " + words.LastIndex.ToText + " rows"

Don’t forget to ReplaceLineEndings before trying to split on line endings.

1 Like

Hi Tim, Ok replacelineendig is for making newline “compatible” on operating systems … and how should I use it? When I write the file, for example, I store “string” + chr (13)

Well, you’re going to want to know for a fact which line ending you’re splitting on. I tend to lean toward the Unix constant. I’ve adjusted your sample to illustrate.

dim strIN as TextInputStream = TextInputStream.Open(PathMyFile)

''READ ALL FILE TXT
dim AllTextFromFileRead as String
AllTextFromFileRead=strin.ReadAll

// Sanitize the line endings to be sure split happens correctly
AllTextFromRead = ReplaceLineEndings(AllTextFromRead, EndOfLine.Unix)

dim words() as String
words = AllTextFromFileRead.Split(EndOfLine.Unix)

messagebox " They are " + words.LastIndex.ToText + " rows"
1 Like

Optimized code :slight_smile: Thanks.