Skip to main content

read_ascii_cols.pro


Pro read_ascii_cols,infile,data,header,ncols,head_length=head_length
;Procedure to read a file of columns of asciii data of unknown length
;ncols specifies number of columns of data
;The keyword head_length specifies number of lines in heade, if omitted then no header lines are read
;first we will open the file and count the number of lines, for this we need a counter variable counter
counter=0
; we also need a variable to read each line into, this is best done using a string which will read an entire line of text at a time
dum=''
; open the file to read from
openr, 1, infile
; openr means open for reading, 1 is just a unit number which we assign to this file, and infile is the filename which
; has been passed into the procedure
;Here we will use a WHILE loop to repeat the reading  and increment the counter until the end of the file is reached  - EOF(1)
WHILE NOT EOF(1) DO BEGIN
    ;read the current line into the variable ?dum?, readf is used for reading formatted data
    readf, 1, dum
    ;increment the counter
    counter++
END
; Each call to readf reads an entire line and moves onto the next
;Now we know how many lines are in the file we close it
close, 1
;Now we open the file again to actually read the data
openr, 1, infile
;If there's a header then create a string array to read it into and read the header
IF keyword_Set(head_length) THEN BEGIN
    header = strarr(head_length)
    readf,1,header
endif
;Create an array to hold the data, we know the number of lines in the file and the number of header lines so we can work out the
; number of data lines (number of rows for the array)
data = fltarr(ncols, counter-head_length)
;Read data, since the data is arranged in rows and columns and the data array is the correct size, we can just read the whole array
; in one go
readf,1,data
;close the file
close,1
END