我在 c 工作。我有两个文件。如果第二个文件中存在,我想问一下在第一个文件的每一行中测试的最佳方法是什么。
我还需要一些示例代码。
谢谢
由于问题有点模糊,“哈希”可能是一个也有点模糊的答案。
#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");
}
只是安吉拉,只要研究一下你指出的做这个家庭作业的 C 书。它很可能有一整章只是关于文件处理的。
对于初学者,您需要熟悉 fopen(和 fclose)、fscanf、fseek 以及可能的 memcmp。