-
-
Save anonymous/22f514bd7e5b16ae857a82b10c3af0c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <ctype.h> | |
#define EXIT_FAILURE 1 | |
#define EXIT_SUCCESS 0 | |
//#define ENTER 10 | |
FILE *FA, *FB; | |
typedef struct lis { | |
char *data; | |
struct lis *next; | |
} list; | |
list *aFirst, *bFirst; | |
void ex(int value); // Выход из программы | |
char *getWord(FILE *f); | |
int main(int argc, char *argv[]) { | |
char *longest, *aWord, *bWord; | |
int length; | |
if(argc != 3){ | |
printf("\nUsage: \"\\path1\\B5_13_3.exe \\path2\\FILEA \\path3\\FILEB\"."); | |
ex(EXIT_FAILURE); | |
} | |
if (!(FA = fopen(argv[1], "r"))) { | |
printf("\nThere is no such file in the direcory."); | |
ex(EXIT_FAILURE); | |
} | |
if (!(FB = fopen(argv[2], "r"))) { | |
printf("\nThere is no such file in the direcory."); | |
ex(EXIT_FAILURE); | |
} | |
longest = NULL; | |
length = 0; | |
while((aWord = getWord(FA))) { //Пока в первом файле есть слова | |
if(strlen(aWord) <= length){ | |
free(aWord); | |
continue; | |
} | |
rewind(FB); | |
while((bWord = getWord(FB))){ | |
if (!strcmp(aWord, bWord)){ | |
free(longest); | |
longest = aWord; | |
length = strlen(longest); | |
free(bWord); | |
break; | |
} | |
free(bWord); | |
} | |
} | |
if(!longest){ | |
printf("\nThere are no matching words in these files."); | |
} | |
else{ | |
printf("\nThe longest word that exists in both files: "); | |
puts(longest); | |
} | |
free(longest); | |
free(aWord); | |
free(bWord); | |
ex(EXIT_SUCCESS); | |
} | |
void ex(int value) { | |
printf("\n"); | |
if(FA) | |
fclose(FA); | |
if(FB) | |
fclose(FB); | |
//printf("\nPress Enter to exit."); | |
//while(getchar() != ENTER); | |
exit(value); | |
} | |
//Возвращает указатель на найденное слово или NULL, если файл кончился. | |
char *getWord(FILE *f){ | |
char c, *word, *tmp; | |
unsigned i, n; | |
i = 0; | |
n = 42; // Начальная длина слова | |
if(!(word = (char *)malloc(n*sizeof(char)))) | |
ex(EXIT_FAILURE); | |
while(1){ | |
c = getc(f); | |
if(isalpha(c)) { | |
if(i == n-1) { // Если слово длиннее отведенной строки | |
n *= 2; | |
if(!(tmp = (char *)malloc(n*sizeof(char)))) | |
ex(EXIT_FAILURE); | |
strcpy(tmp, word); | |
free(word); | |
word = tmp; | |
tmp = NULL; | |
} | |
word[i] = c; | |
word[i+1] = '\0'; | |
i++; | |
} | |
else { | |
if(i != 0){ | |
return word; | |
} | |
if(c == EOF){ | |
return NULL; | |
} | |
i = 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment