• Welcome to OS2World OLD-STATIC-BACKUP Forum.
 

News:

This is an old OS2World backup forum for reference only. IT IS READ ONLY!!!

If you need help with OS/2 - eComStation visit http://www.os2world.com/forum

Main Menu

Get first and last line in text file

Started by jep, 2008.03.31, 12:45:22

Previous topic - Next topic

jep

Marked as: Advanced
Hello,

here's an example on how to parse the first row of a file and then the last one without looping through the whole file.

If the file is large, then it has to load the entire file into memory, but if you modify the code to read the file from a position (har coded as 1) such as "max( 1, f_size - 1000 )" then you'll be able to handle only the last few rows which is more efficient.

The first function is just a wrapper to allow named return variables but not expose the internal data of the actual function.

/* Params: FileName, get_data_from_first_row_into_variable, get_data_from_last_row_into_variable */
rxGetErrBoundaries:
    if ARG() < 1 then Return ''
   
    retval = rxGetErrBoundaries_( ARG(1), 'start_val', 'stop_val' )
   
    if length( ARG(2) ) > 0 then
        interpret ARG(2)||' = start_val'
    if length( ARG(3) ) > 0 then
        interpret ARG(3)||' = stop_val'
Return retval

rxGetErrBoundaries_: procedure expose start_val stop_val
    fileName = ARG(1)
    if FileExist( fileName ) then
    do
        f_size = stream( fileName, "c", "QUERY SIZE" )
        call stream fileName, "c", "OPEN READ"
       
        fileContents = charin( fileName, 1, f_size )
   
        call stream fileName, "c", "CLOSE"

        interpret "parse value fileContents with "||ARG(2)||"','."

        linePos = lastpos( d2c(13)||d2c(10), fileContents )
        if linePos > 0 then
        do
/* Modify to meet your need, this one get the value present before "," */
            interpret "parse var fileContents 1 fileContents +"||linePos||" input','."
            input = changestr( d2c(13), changestr( d2c(10), input, '' ), '' )
               
            if length( input ) > 0 then
            do
                interpret ARG(3)||' = input'
                Return input.i
            end
        end
    end
Return ''