Reading from file into array, line by line

时间:2015-10-30 21:53:27

标签: c file

I am trying to read from a file in C. My code is the following. It seems to read everything fine into the array, but when I try to print it, I get the error Segmentation fault (core dumped)

  FILE *fp;
   char * text[7][100];
   int i=0;

   fp = fopen("userList.txt", "r");

   //Read over file contents until either EOF is reached or maximum characters is read and store in character array
   while(fgets((*text)[i++],100,fp) != NULL) ;

   printf("%s", &text[0]);

   fclose(fp);

Can someone point me in the right direction?

I have tried reading and copying solutions from other similar cases, but they are extremely specific to the user.

2 个答案:

答案 0 :(得分:2)

So part one, you don't need a pointer to a char[][]:

char text[7][100];

Part 2, just deference your array of strings like a normal person, nothing fancy here:

while(fgets((text)[i++],100,fp) != NULL) ;

Live example: http://ideone.com/MADAAs

Some things to watch out for:

  1. If your input file has more than 7 lines you are going to have problems.
  2. Why is “while ( !feof (file) )” always wrong?

答案 1 :(得分:0)

char * text[7][100]; //wrong - this is 2 diminutions array of char pointers, replace it with 
char text[7][100];

while(fgets((*text)[i++],100,fp) != NULL) ; // replace this with
 while(fgets(&text[i++][0],100,fp) != NULL) ; 

NOTE: this code will work in the current scope of the function (on the stack) if you need to use it outside the scope of current scope , allocate some memory on the heap and use the pointers of the heap.