gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:30:14 24 4
gpt4 key购买 nike

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

#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;

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

我的文件指针是否不正确,或者我是否弄乱了某个地方的数据类型导致了这种情况?

最佳答案

首先你应该改变你的 while 循环

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

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

由于 != 的优先级高于 =,因此您的 while 循环总是有问题

关于在 C 中逐个字符比较文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32136799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com