user3260745 February 2016

Read A file line by line into an Array in C

I'm having a lot of difficulty doing this! What I do is get the first line to initialize an array of pointers, then want to point those blocks to variables that contain the string from the text document. However; even when I read all the values into the array they are all pointing to the same variable which changes as the file is being read. Is there way I can copy those values into the array without them all pointing to the changing line as the file is being read?

int main(void){
FILE * fp;
char line[256];
int i = 0;
int digit = 0;

fp = fopen("testfile","r");

if(fp == NULL){
    printf("Cannot Open File");
}
fgets(line,sizeof(line),fp);
digit = atoi(line);
printf("digit = %d\n",digit);
char *rest[digit];
while(!feof(fp)){
    while (i < digit){
        fgets(line,sizeof(line),fp);
        fgets(line,sizeof(line),fp);
        printf("line = %s",line);
        char arr[sizeof(line)+1];
        strcpy(arr,line);
        rest[i] = arr;
        printf("restaurant = %s",rest[i]);
        i++;
    }

the text file is as follows:

6
Outback Steakhouse
Red Robin
Max & Erma’s
Chipotle
Panera
BW3
8
Stephanie 5 3 2 4
Chris 4 6 5 1
Peter 5 2 4 1
Josh 1 4 3 6
Jessica 5 2 3 4
Al 6 4 2 3
Adam 5 1 3 2
Eric 1 4 3 5

Answers


Zbynek Vyskovsky - kvr000 February 2016

You need to copy the values into dynamically allocated memory. strdup will do. Replace:

    char arr[sizeof(line)+1];
    strcpy(arr,line);
    rest[i] = arr;

With:

    rest[i] = strdup (line);

Also you call fgets twice.

Additionally, when line is too long, it will be not zero terminated. To make it safe always assign zero at the end of line.

Post Status

Asked in February 2016
Viewed 1,580 times
Voted 8
Answered 1 times

Search




Leave an answer