C语言 使用 getc 逐行读取不起作用



我需要从文件中逐行读取,这是我的代码:

FILE *fp1;
    char c;
    int n = 500;
    int counter = 0 ;
    char *buffer;
    buffer = (char*) realloc(buffer, n);
    strcpy(buffer, "");
    fp1 = fopen("text.txt","r");
    if(fp1 == NULL)
    {
        perror("Error in opening file");
        return;
    }
 do
    {
        c = fgetc(fp1);
//My specification .. stop reading if you read E
        if( c == 'E' )
        {
            break ;
        }
        if (c == 'n') {
            printf("%sn", buffer);
            counter=0;
            strcpy(buffer, "");
        }
        else{
            counter++;
/*handling overflow*/
            if (counter > n) {
                n+=100;
                buffer = (char*) realloc(buffer, n);
            }
            strncat(buffer, &c,1);
        }
    }while(!feof (fp1));

问题是代码无法正常工作,它打印的行数比原始文本文件多。谁能帮忙找出原因?

附言我知道getc()有替代品,但我需要使用它。

更新
我将缓冲区的初始化从原始更改为:

 char *buffer = NULL;

以及与此相关的所有其他strcpy()

 *buffer = NULL;

但仍然是同样的问题。

使用 !feof (fp1( 作为外部 while 循环条件。您没有检查文件末尾。

buffer = (char*)malloc(sizeof(char)* n);

我刚刚更改了您的缓冲区分配代码,保持其他所有内容不变。似乎对我来说工作正常。

最新更新