我在c工作。 我有两个文件。我想问一下,如果存在于第二个文件中,从第一个文件中测试每一行的最佳方法是什么。
我还需要一些示例代码。
THX
答案 0 :(得分:0)
答案 1 :(得分:0)
由于问题有点模糊,“哈希”可能是一个有点模糊的答案。
答案 2 :(得分:0)
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int compareFiles(const char * filename_compared, const char *filename_checked, int *matched)
{
int matches = 0;
int lines = 0;
char compare_line[10000];
char check_line[10000];
char *compare;
char *check;
FILE *f_compare;
FILE *f_check;
f_compare = fopen(filename_compared,"r");
if ( f_compare == NULL )
{
printf("ERROR %d opening %s\n",errno,filename_compared);
return EXIT_FAILURE;
} else { printf("opened %s\n",filename_compared); }
f_check = fopen(filename_checked,"r");
if ( f_check == NULL )
{
printf("ERROR %d opening %s\n",errno,filename_checked);
return EXIT_FAILURE;
} else { printf("opened %s\n",filename_checked); }
compare = fgets(compare_line,sizeof(compare_line),f_compare);
while ( ! feof(f_compare) )
{
lines++;
fseek(f_check,0,0);
check = fgets(check_line,sizeof(check_line),f_check);
while ( ! feof(f_check) )
{
if ( strcmp(compare_line,check_line) == 0 )
{
matches++;
break;
}
check = fgets(check_line,sizeof(check_line),f_check);
}
compare = fgets(compare_line,sizeof(compare_line),f_compare);
}
*matched = matches;
printf("%d lines read in first file and %d lines matched a line in the 2nd file\n",lines,matches);
fclose(f_check);
fclose(f_compare);
return EXIT_SUCCESS;
}
int main(int argc, char *argv[])
{
int matches;
if ( argc < 3 )
{
printf("ERROR: You must enter the two input filenames\n");
return EXIT_FAILURE;
}
int return_code = compareFiles(argv[1],argv[2],&matches);
if ( return_code == EXIT_SUCCESS )
printf("%d lines in %s matched a line in %s\n",matches, argv[1],argv[2]);
else
printf("there was an error in processing the files\n");
}
答案 3 :(得分:0)
Just Angela,只是研究你所指的C书,只做家庭作业。它可能只有一整章文件处理。
对于初学者,你需要熟悉fopen(和fclose),fscanf,fseek和memcmp。