[英]Compare two text files in C [closed]
我想编写一个比较两个文本文件的程序,当 text1 中的一行与 text2 中的一行相同时,程序输出第一个文件中的行号,然后输出第一个文件中的行号第二个文件,然后是该行的实际文本。
我有两个输入文件。
文件1.txt
AAA
BBB
CCC
文件2.txt
DDD
CCC
FFF
output 必须是:
Line number from text1: 3, Line number from text2: 2, Text from lines: CCC
到目前为止我所拥有的:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
void compareFiles(FILE *fp1, FILE *fp2, FILE *fp3)
{
// Read chars
char ch1 = getc(fp1);
char ch2 = getc(fp2);
// Current line in both files
int line = 1;
//int linen1 = 1;
//int linen2 = 1;
// Store lines
char line1[1024];
char line2[1024];
// Line 1 from file 1 is not read; l1 from file 2 is not read
bool readL1 = false;
bool readL2 = false;
// iterate loop till end of file
while (ch1 != EOF && ch2 != EOF)
{
//Add chars to line string
strncat(line1, &ch1, sizeof(line1));
strncat(line2, &ch2, sizeof(line2));
//Check if it's the end of line 1
if (ch1 == '\n')
{
readL1 = true;
}
// Check if it's the end of line 2
if (ch2 == '\n')
{
readL2 = true;
}
// If both lines are fully read compare them
if (readL1 && readL2)
{
//If the strings are different print them
if (strcmp(line1, line2) != 0)
{
fprintf(fp3, "Line: %d\t", line);
fprintf(fp3, "L1: %s\t", line1);
fprintf(fp3, "L2: %s\t", line2);
strcpy(line1, "");
strcpy(line2, "");
}
//Mark lines as not read
readL1 = false;
readL2 = false;
line++;
}
//If end of line is not reached get the next char
if (!readL1)
{
ch1 = getc(fp1);
}
if (!readL2)
{
ch2 = getc(fp2);
}
}
}
int main()
{
//Open files
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");
FILE *fp3 = fopen("file3.txt", "w");
if (fp1 == NULL || fp2 == NULL)
{
printf("Error : Files not open");
exit(0);
}
compareFiles(fp1, fp2, fp3);
//Close files
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
任何帮助表示赞赏:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.