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.