Reputation: 105
I'm trying to develop a function that reads each line of a text file and the it stores them in an array of strings (char**) but fgets() doesnt seem to work, it always return a null character.
Here is the function
char** getLines(FILE* fp){
char** lines;
int numberOfLines; //number of lines int the file
char ch; //aux var
int i; //counter
while(!feof(fp)){
ch = fgetc(fp);
if( ch == '\n'){
numberOfLines++;
}
}
lines = malloc(numberOfLines*sizeof(char*));
if (lines==NULL){
fprintf(stderr,"Error, malloc failed");
exit(1);
}
for(i = 0; i<numberOfLines; i++){
lines[i] = malloc(MAX_LENGTH*sizeof(char)); //MAX_LENGTH = 128
}
i=0;
while(fgets(lines[i], MAX_LENGTH,fp)){
printf("Line %d: %s \n",i,lines[i]);
i++;
}
return lines;
}
The function never gets inside the while loop so it doesn't print anything I'm also using a very simple input file:
test line 1
test line 2
test line 3
test line 4
Hope you can help me, Thank you in advance.
Upvotes: 2
Views: 1693
Reputation: 701
You are already on the end of the file before entering the while loop.
Take a look here http://en.cppreference.com/w/cpp/io/c/rewind
Moves the file position indicator to the beginning of the given file stream. The function is equivalent to std::fseek(stream, 0, SEEK_SET); except that end-of-file and error indicators are cleared. The function drops any effects from previous calls to ungetc.
Check if this works:
char** getLines(FILE* fp){
/* ...... */
i=0;
rewind(fp); // Rewind here
while(fgets(lines[i], MAX_LENGTH,fp)){
printf("Line %d: %s \n", i, lines[i]); // Also use the index as first parameter
i++;
}
return lines;
}
Upvotes: 3