Click to See Complete Forum and Search --> : quick help? textfile and arrays


hetman
08-14-2002, 01:04 PM
just wondering if anyone can help me out.
i want to read a text file into an array, so that each line in the text file in in an array, ex:
text file:
blah1
blah2
blah3

array:
myarray[0]="blah1"
myarray[1]="blah2"
myarray[2]="blah3"

is that possible?

btw... the language is C

bwkaz
08-14-2002, 03:32 PM
Make myarray a char **, and you should have it.

Use something like this to set it up:

char **myarray;

/* <put number of lines into numlines, somehow> */

if((myarray = malloc(numlines * sizeof(char *))) == 0) {
printf("malloc failed.\n");
exit(1);
}

for(i=0; i<numlines; i++) {
/* <get the length of line i here, put it into length> */

if((myarray[i] = malloc(length * sizeof(char))) == 0) {
printf("malloc failed.\n");
exit(1);
}
}

/* now read the data into each line, using whatever file-access functions you happen to like. */