Reputation: 99
I am making a program in c that reads line by line and does some operation on the elements of every line. I am calling my read_row function like this.
while(filePointer!=NULL)
{
int result=readRow(filePointer,headerRow,lineRow);
printf("The value of row is |%d|\n",result);
}
Inside my read_row function I am using get c to traverse through the line.
cc=getc(fp);
while((cc!='\n') && (cc!= EOF))
{
*line=cc;
line++;
if(cc==',')
{
counterr++;
}
cc=getc(fp);
}
if(cc==EOF)
{
fp=NULL;
}
I am trying traverse through all the lines. However, this loop is infinite as file pointer never goes to null. I have tried to set the file pointer to null if the cc equals to EOF. However, this did not help at all. Therefore, please explain how should I properly terminate that loop. I believe that '\n' is coming before the EOF.Therefore, the file pointer is not getting to null. I have to do it using the file Pointer, as I have already made a very big program based on that logic. Moreover, I could only find examples that used methods like fgets() to traverse.
Upvotes: 1
Views: 1383
Reputation: 16540
the posted code has several significant errors.
For instance setting the parameter `FILE* fp = NULL; is only changing the copy of the actual fp, not the fp back in the calling function.
after the FILE * fp
parameter is changed to FILE **fp
and the call to the function is modified to match:
before modifying the fp, pass that parameter to fclose(*fp)
otherwise the file is still open but the pointer to the associated file descriptor is destroyed, so the file cannot be closed.
Upvotes: 0
Reputation: 29976
When you pass a pointer to the function and then change it, you are actually changing the copy of that pointer, not the pointer itself. You need to pass a pointer to pointer for this to work, here's a small example:
int a = 2;
int b = 5;
//note the pointer to pointer:
void foo(int **ptr)
{
*ptr = &b;
}
int main() {
int * ptr = &a;
foo(&ptr);
printf("%d", *ptr); // prints 5
}
So in your case the readRow
should accept FILE**
, and you should call it as readRow(&filePointer...
Upvotes: 7