在C中逐个字符地比较文本文件

时间:2015-08-21 09:19:54

标签: c io char

我正在写一个小程序,其内容如下:
执行时,将两个文本文件作为参数 逐个字符地比较每个文本文件,向用户显示每个比较是否成功 当两个字符(在相同位置)不相同时,将向用户告知,并且程序结束 如果两个文本文件完全相同,则也会告诉用户,程序结束。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) // define main procedure, taking an command line argument
{
    int ch, ch2; // index for current character
    FILE *fp; // pointer to file
    FILE *fp2;
    unsigned long count = 0;

if (argc != 3) //
{
    printf("Usage: %s filename \n", argv[0]);
    exit(EXIT_FAILURE);
}

if ((fp = fopen(argv[1], "r")) == NULL) // check for 'cannot open' error in first file
{
    printf("Can't open %s\n", argv[1]);
    exit(EXIT_FAILURE);
}
else if ((fp2 = fopen(argv[2], "r")) == NULL) // check for 'cannot open' error in second file
{
        printf("Can't open %s\n", argv[2]);
        exit(EXIT_FAILURE);
}

while ((ch = getc(fp) != EOF) || (ch2 = getc(fp2) != EOF)) // while both files still have characters remaining
{
    printf("\n %d %d \n", ch, ch2); // print both characters (debugging purposes)
    if (ch == ch2) // if two characters are same at current position
    {
        printf("FILES ARE SAME AT POSITION %d", count); // report to user
        count++; // increase count
    }
    else
    {
        printf("FILES ARE NOT NOT NOT SAME AT POSITION %d", count); // report that files are not same at current position
        fclose(fp); // close files
        fclose(fp2);
        exit(EXIT_FAILURE); // exit
    }
}

fclose(fp);
fclose(fp2);
printf("FILES ARE THE SAME THROUGHOUT!");

return 0;

但是,程序在比较时不显示文件中的随机字符,导致无限循环和错误执行。

我的文件指针不正确,还是我把某个数据类型搞砸了?导致这种情况?

2 个答案:

答案 0 :(得分:3)

首先你应该从

改变你的while循环
unsigned long

while ((ch = getc(fp) != EOF) || (ch2 = getc(fp2) != EOF))

由于while (((ch = getc(fp)) != EOF) || ((ch2 = getc(fp2)) != EOF)) 的优先级高于!=,因此您的while循环始终存在问题

答案 1 :(得分:1)

在此代码中考虑parens的位置:

if ((fp = fopen(argv[1], "r")) == NULL)

现在仔细看看,比较这段代码中parens的位置:

while ((ch = getc(fp) != EOF) || (ch2 = getc(fp2) != EOF))

您是否注意到任何不一致之处?也许你想写这个:

while ((ch = getc(fp)) != EOF || (ch2 = getc(fp2)) != EOF)

您的计划还有其他问题。在printf("FILES ARE SAME AT POSITION %d", count);中,您告诉printf打印由int表示的count,但count不是int ...您应该使用{ {1}} %lu值。