为什么此代码会打印空字符以及为什么它在两个文件中都找到空字符?

问题描述 投票:0回答:1
bool isIdentical(FILE *file1, FILE *file2) //this fun tell me files is identical or no
{
    // this must have char1 in file1?  
    char c1 = fgetc(file1);

    // this must have char2 in file2? 
    char c2 = fgetc(file2);

    while (c1 != EOF && c2 != EOF)  //check if files reached to end 
    {
        c1 = fgetc(file1);
        c2 = fgetc(file2);
        if (c1 != c2)
            return 0;

        // I expect to print each char in to files but it actual print NULL  
        printf("%c %c\n", c1, c2);
    }

    // this to check if two files reached to end without returning 0
    if (c1 == EOF && c2 == EOF)
        return 1;
    else
        return 0; // then the files don't have the same length hence are not identical
}
c file printf eof fgetc
1个回答
3
投票

存在多个问题:

  • 您必须使用

    c1
    (而不是
    c2
    )类型定义
    int
    char
    ,才能可靠地测试
    EOF
    fgetc()
    有257个不同的返回值,
    char
    只能保存256个不同的值。

  • 进一步模式,永远不会为两个文件的第一个字节调用

    printf
    语句,并且可以使用
    c1
    c2
    都等于
    EOF
    来调用,这不是
    0
    ,但更有可能是
    -1 
    。对于这些字节,您可能会在终端上看到有趣的字符。

  • 您的

    printf
    调用会输出原始字节值,如果文件具有二进制内容,这可能会在终端中导致虚假行为。

  • 您还应该使用以二进制模式打开文件(使用

    "rb"
    )以确保
    fgetc()
    不会以系统特定的方式翻译文件内容。

这是修改后的版本:

#include <stdbool.h>
#include <stdio.h>

bool isIdentical(FILE *file1, FILE *file2)  // compare file contents
{
    int c1 = fgetc(file1);
    int c2 = fgetc(file2);

    // loop until one or both files reach end of file
    while (c1 != EOF && c2 != EOF)
    {
        if (c1 != c2)
            return 0;

        printf("%d %d\n", c1, c2);

        c1 = fgetc(file1);
        c2 = fgetc(file2);
    }

    // return TRUE if both files have the same length
    return (c1 == EOF && c2 == EOF);
}

这是一个更简单的替代方案,测试较少且没有重复的函数调用:

#include <stdbool.h>
#include <stdio.h>

bool isIdentical(FILE *file1, FILE *file2)  // compare file contents
{
    for (;;) {  // unconditional loop
        int c1 = fgetc(file1);
        int c2 = fgetc(file2);

        if (c1 != c2)
            return 0;
        if (c1 == EOF)
            return 1;

        printf("%d %d\n", c1, c2); // print identical byte values
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.