Skip to main content

5.9) Example Procedure


Pro read_ascii_cols, infile, data, header, ncols, head_length=head_length
; Procedure to read a file of columns =of ascii data of unknown length
; ncols specifies the number of columns of data
; The keyword head_length specifies the number of lines of header test,
; if omitted 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=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 the file for reading
; 1 is a unit number which we assign to this file
; infile is the filename which has been passed into the procedure
; here we will use a WHILE loop to repeat reading and incrementing;
; 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