Read A file line by line into an Array in C -


i'm having lot of difficulty doing this! first line initialize array of pointers, want point blocks variables contain string text document. however; when read values array pointing same variable changes file being read. there way can copy values array without them pointing changing line file being read?

int main(void){ file * fp; char line[256]; int = 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 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 

you need copy values dynamically allocated memory. strdup do. replace:

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

with:

    rest[i] = strdup (line); 

also call fgets twice.

additionally, when line long, not 0 terminated. make safe assign 0 @ end of line.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -