逐个字符地比较两个文件 - C 中的文件结尾错误

Comparing two files char by char - end of file error in C

我有一个具体问题。我必须从两个文件中读取字符串,然后逐个字符地比较它们,并告诉它们差异在哪一行以及它们有多少个字符不同。我已经制作了指针和所有东西,但问题是当它到达第一个文件的末尾时(它只需要读取较短文件的长度)我无法比较最后一个字符串,因为我的 for 循环一直持续到'\n',最后一行没有 \n。但另一方面,如果我将 '\0' 放入 for 循环中,它会给我一个错误的结果,因为它也将 '\n' 计为 char。我该如何处理这个问题?建议?我不想使用 strcmp() 因为我需要计算字符差异,并且还有一些其他条件需要满足。这是我的问题:

while(!feof(fPointer)){
    zeichnen = 0;
    fgets(singleLine, 150, fPointer);
    fgets(singleLine2, 150, fPointer2);
    length = strlen(singleLine);            // save the length of each row, in order to compare them
    length2 = strlen(singleLine2);
    if(length <= length2){
        for(i=0; singleLine[i] != '\n'; i++){
                singleLine[i] = tolower(singleLine[i]);
                singleLine2[i] = tolower(singleLine2[i]);
            if(singleLine[i] != singleLine2[i]){
                     zeichnen++;
                }
        }
        printf("Zeile: %d \t Zeichnen: %d\n", zeile, zeichnen);   // row, char
for(i=0; i < min(length, length2); i++) {
      if ( singeLine[i] == '\n' || singleLine2[i] == '\n')
        break;
       /* Do work */
}       

替代方法是使用逻辑与运算符来测试 for 循环条件部分中的两个或多个条件。

来自 fgets 手册页:

char *fgets(char *s, int size, FILE *stream);

fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.

所以你应该有 while(true) 循环并检查输入结束的两个 fgets return 值。