私はcで働いています。私は2つのファイルを持っています。2番目のファイルに存在する場合、最初のファイルの各行でテストする最良の方法は何ですか.
サンプルコードも必要です。
どうも
ただアンジェラ、この宿題をするためにあなたが指摘した C の本を勉強してください。ファイル処理に関する章全体が含まれている可能性があります。
手始めに、fopen (および fclose)、fscanf、fseek、および場合によっては memcmp に精通する必要があります。
質問は少しあいまいなので、「ハッシュ」も少しあいまいな答えになる可能性があります。
#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");
}
自分でコーディングする代わりに diffviewer を試してみませんか?
それ以外の場合、C では、文字を最初から最後まで比較し、それぞれの位置の違いを覚えて、それらを出力しますか?