Read ASCII string from external file

Hi, I'm working on a model importer/exporter for a game which I am coding in MAXSCRIPT. I'm getting trouble doing the thing I mentioned in the title. Well actually I have written a script that does the job but it is slow & takes almost 5 seconds to find 4 bytes of data in a 220 kb file.
--------------------------------------------------------------
function findstr filename=
(
fstream= fopen filename "rb"
fseek fstream 0 #seek_end
end= ftell fstream
pos= 4
while (pos <= end) do
(
fseek fstream pos #seek_end
val= readlong fstream #unsigned
/* 860639043 is the value the "readlong" function gives when the data in question is read */
if (val == 860639043) then exit
pos= pos+1
)
fseek fstream pos #seek_set
pos= ftell fstream
fclose fstream
return pos
)
--------------------------------------------------------------
This is a binary file so I can't use skiptostring(I tried it). "Readstring" doesn't work too well either.
this 4s is very inefficient, a small hex editor does this job in no time. Please could I have some feedback on how to write a better script for this job (as well as reading/writing data from/to external files in general?)

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Graph's picture

return you can but dont have

return you can but dont have to use (if you wish to then only at the END of a function)
exit is one of them overhead thingies you really shouldnt use as it kinda shoots hot liquid led into your legs ;)
and you should get used to always defining the scope of your vars, yes even in a function ..where they are local by default

Raphael Steves

seggaeman's picture

skip 'exit' and 'return'

Thanks that's a nice way of bypassing the exit and return! I think the pointer will have to be readjusted after each "readlong" however otherwise I risk missing the data I am looking for, if it gets split between successive reads.

On I own I managed to speed up the script by using the end of the file as base for the pointer instead of the beginning (the data is always closer to the end in the files I am reading from). I'll rewrite it again now without the "exit" and "return".

veneta's picture

skip 'exit' and 'return'

as i know 'exit' slow down a lot ('return' too), try this...

-- if return -1 you'll know that the long is not found
function findstr filename=
(
   fstream = fopen filename "rb"
   run = true ; pos = -1
   while (not eof fstream) or (run) do
   (
      if (readlong fstream #unsigned) == 860639043 do
      (
         run = false ; pos = ftell fstream
      )
   )
   fclose fstream ; pos
)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.