如何仅使用文件指针正确遍历C循环

WOW*_*WOW 1 c pointers loops file while-loop

我在c中创建一个逐行读取的程序,并对每行的元素进行一些操作.我正在调用我的read_row函数.

while(filePointer!=NULL)
{
        int result=readRow(filePointer,headerRow,lineRow);
        printf("The value of  row is |%d|\n",result);
}
Run Code Online (Sandbox Code Playgroud)

在我的read_row函数中,我使用get c遍历该行.

 cc=getc(fp);
    while((cc!='\n') && (cc!= EOF))
    {

            *line=cc;
            line++;  
            if(cc==',')
            {
                counterr++;
            }
            cc=getc(fp);

    }  

    if(cc==EOF)
    {
        fp=NULL;
    }
Run Code Online (Sandbox Code Playgroud)

我正试图遍历所有的路线.但是,这个循环是无限的,因为文件指针永远不会变为null.如果cc等于EOF,我试图将文件指针设置为null.但是,这根本没有帮助.因此,请解释我应该如何正确终止该循环.我相信'\n'在EOF之前出现.因此,文件指针不会变为null.我必须使用Pointer文件来完成它,因为我已经基于该逻辑创建了一个非常大的程序.而且,我只能找到使用fgets()等方法遍历的例子.

Sin*_*all 7

当您将指针传递给函数然后更改它时,实际上是在更改该指针的副本,而不是指针本身.你需要传递一个指向指针的指针,这是一个小例子:

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
}
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下readRow应该接受FILE**,你应该称之为readRow(&filePointer...