Why does my buff [0] print the last line of the file, and how can I make all the elements of the array available outside the loop?

FILE *fp; fp = fopen("test.db", "rb"); int i = 0; char str[126]; char *buff[126]; while (!feof(fp)) { if (fgets(str, 126, fp)) { buff[i] = str; } i++; } printf("%sn", buff[0]); 
  • @badsanta; To format a code, select it with the mouse and click on the button 101010 of the editor. - Zowie
  • Save them. Because strings are read in str, but the sibling with buff is generally outside of the mind. All buff [i] elements are equal to str. (And well, if fgets is called less than 126 times) Copying the contents of str to buff [i] = str does not occur, and there is no place to copy there. - alexlz

2 answers 2

Why does my buff [0] print the last line of the file?

Because you are reading the next line in char str[126] , respectively, the previous value of the str array is overwritten. Buf[0] essentially points in the same Buf[i] - to str , which contains the last read line.

How can I make all elements of an array available outside the loop?

Read in different lines

 while(!feof(fp)) { if(fgets(str, 126, fp)) { char* curr = malloc(126); // создать новую строку memcp(curr, str, 126); // скопировать в нее прочитанное содержимое buff[i++]=curr; } } 
  • >> memcp (curr, str, 126); // copy the memcpy read contents into it :) symbol y - forgot, and everything works, thank you. - Stepanov Max
  • And why exactly 126? What, strlen () is no longer working? - avp
  • 126 for a clearer explanation. - fogbit

buff [i] = strdup (str) will solve your problem.

Inside, strdup () does malloc (), so it may be necessary to free memory.

  • strdup is not included in the standard like. - fogbit
  • I worked with any libc. If somewhere it is not, then add up is not a problem. - avp 2:41 pm