Skip to content

Instantly share code, notes, and snippets.

/proj Secret

Created March 28, 2017 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/22f514bd7e5b16ae857a82b10c3af0c9 to your computer and use it in GitHub Desktop.
Save anonymous/22f514bd7e5b16ae857a82b10c3af0c9 to your computer and use it in GitHub Desktop.
#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