331
Rexx / Get first and last line in text file
« on: 2008.03.31, 11:45:22 »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.
Code: [Select]
/* 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 ''


*/