Notifications
Clear all

[Closed] Number of lines of a file

Hi,

is there a faster way to read the number of lines?


  MyDatName = "Import.txt"
  MyFile = openfile MyDatName
  
  maxlen = 0
  
  while not eof MyFile do
  (
  	maxlen =maxlen + 1
  	skiptonextline MyFile 
  )
  	
  seek MyFile 0
  Print maxlen 

Thanks,
Oli “blenderman”

7 Replies

Well, you could read the whole file into a string then filter it by a newline token:


fin = openFile "Thefile.txt"

---this code is straight from the help file---
seek fin #eof
maxlen=filepos fin
seek fin 0
res = readChars fin maxlen errorAtEOF:false
------------------------------------------

lineNums = (filterString res "
").count
close fin

print lineNums

The downside to this method is it doesn’t count empty lines, but that also may be a good thing.

I also have no idea if it’s faster.

1 Reply
(@bobo)
Joined: 11 months ago

Posts: 0

 fin = openFile "Thefile.txt"
 
 ---this code is straight from the help file---
 seek fin #eof
 maxlen=filepos fin
 seek fin 0
 res = readChars fin maxlen errorAtEOF:false
 ------------------------------------------
 
 lineNums = (filterString res "
" [b][b]splitEmptyTokens[/b][/b][b][b]:true[/b][/b]).count
 close fin
 
 print lineNums
 

The SplitEmptyTokens:true option is available in Max 8 and higher and will create empty elements when two tokens are next to each other. It should avoid the above downside.

Thank you erilaz for the new solution and also to Bobo thanks for the optimization. Unfortunatly, the new solution is up to half a minute slower.

Thanks for your Help!

 PEN

How about a cheat of some sort, just off the top of my head and not tried.

readDelimitedString f “Some string that can’t be found”

Now you are at the end of the file.

seek f ((filePos-100) f)

skiptoNextLine…

How ever in writting this there is know way to know where you are in the file as far as lines go only position I think. Just a thought.
[font=Verdana][/font]

Not sure if this is faster, but here’s an alternative method using .NET:

((dotNetClass "System.IO.File").ReadAllLines "Thefile.txt").count

Cheers,
Martijn

:wip: Oh Yes

MaxCode = 20 Seconds VS .NETcode = 0 Seconds

Thank you Martijn! And thanks for your thougths Paul. I love CgTalk…

Cheers,
Oli “blenderman”

 PEN

Nice one, that is far better.