Re: loading a flat file into an array
Posted in 1993
stuart@jane.sas.upenn.edu (Stuart Tener) writes:
>This is probably a relatively simple programming problem for the
>experienced informix programmers in this group, but here goes.
>Let us say for the sake of argument that I have a file which is plain
>ascii text. Each line of text is 50 characters in length, and there are
>5 lines in this file.
>How could I load this file line by line into an array where each element
>of the array (defined as 50 characters I guess) would hold a single line
>of the file.
>Then, how would I do this if I didn't know the length of each record or
>how many there were?
The only good ways I can think of required calls to c functions or
creating a temp table.
The c approach would be to call a c function that opens the file,
then a loop that calls a c functions that returns a line at a time,
and returns a NULL when reading is done, and one that closes the file:
CALL c_fopen(filename)
LET x = 0
WHILE TRUE
LET x = x + 1
IF x > max boundry of array THEN
EXIT WHILE
END IF
LET array[x].line = c_stringfetch()
IF array[x].line IS NULL THEN
# reached the end of the file
EXIT WHILE
END IF
END WHILE
# decrement x so that it holds the count of lines filled
LET x = x - 1
# close the file
CALL c_fclose(filename)
I leave it to others better at writing c code from their heads than I to
fill in the c functions.
The temp table approach:
# create a temp table with a single column sized to be the max width
# of any line in the file
CREATE TEMP TABLE fillarray (eachline CHAR(80))
# load the temp table from the file. Each line will be a row in the
# table.
LOAD FROM filename INSERT INTO fillarray
# fill the array
DECLARE c_fillarray CURSOR FOR SELECT eachline FROM fillarray
LET x = 1
FOREACH c_fillarray INTO array[x].line
LET x = x + 1
IF x > max size of array
EXIT FOREACH
END IF
END FOREACH
# decrement x so that it holds the count of lines filled
LET x = x - 1
================
Dennis J. Pimple
Informix CSE / Denver
303-850-0210