View Full Version : Number of lines of a file
blenderman0815 09-17-2008, 01:08 PM 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"
|
|
erilaz
09-17-2008, 01:33 PM
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 "\n").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. :D
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 "\n" splitEmptyTokens:true).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.
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.
blenderman0815
09-17-2008, 02:17 PM
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!
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.
magicm
09-17-2008, 02:49 PM
Not sure if this is faster, but here's an alternative method using .NET:
((dotNetClass "System.IO.File").ReadAllLines "Thefile.txt").count
Cheers,
Martijn
blenderman0815
09-17-2008, 03:01 PM
: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"
Nice one, that is far better.
CGTalk Moderation
09-17-2008, 03:39 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.
vBulletin v3.0.5, Copyright ©2000-2013, Jelsoft Enterprises Ltd.