Hugh
Hugh

Reputation: 31

How to store a string from a text file in an array in C

I want to read a text file into a string array and be able to access the array contents through a loop. The code I have allows me to store only the last line of the text file instead of the entire file; where am I going wrong?

#define MAX 10000

int main (int argc, char *argv[])
{
    FILE *fp;
    char str[MAX];
    char *x[MAX];
    int i =0;
    char y[MAX];

    if((fp = fopen("550.txt", "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);}

    while(!feof(fp)) {
        while(fgets(str, sizeof str, fp)) {
            x[i]= str;
            printf("%s", str);
            printf("%s", *(x+i));
            i++;
        }
  }


for(i=0;i<100;i++){
    printf("%s", *(x+i));
}

   fclose(fp);

  return 0;
}

Upvotes: 2

Views: 10672

Answers (3)

Richard Cook
Richard Cook

Reputation: 33099

You only allocate one string array str. At each iteration through the loop you are simply overwriting str. The assignment x[i] = str assigns the pointer value of str to x[i]. You'll notice that each member of the array x points to the same buffer str at the end of the loop. You need to create multiple buffers.

One way to do this is to define the maximum number of lines using #define LINES 100 and then to declare x as follows

char x[LINES][MAX];

and then perform a strcpy at each iteration:

while(fgets(str, sizeof str, fp)) {
    strcpy(x[i], str);
    printf("%s", str);
    printf("%s", *(x+i));
    i++;
}

Note that you should consider using the strncpy method instead of strcpy and check the return value to ensure that the buffers do not overrun.

Upvotes: 3

pm100
pm100

Reputation: 50190

you are not stroing the line you read anywhere. It is buffered into str but the you overwrite it with the next line. use strdup.

x[i] = strdup(str);

Upvotes: 0

RichieHindle
RichieHindle

Reputation: 281665

You need to make a copy of each string:

x[i] = strdup(str);

What you're doing at the moment is making each x[i] point to the same buffer, which will contain the last line of the file once you've finished.

(Note: you'll also need to free() all of the x[i] strings you create with strdup().)

Upvotes: 1

Related Questions