#include <stdio.h>
#include <string.h>
#define STR_LENGTH 200
 
int AnagramCheck(char* fileName);
 
int main(void) {
    char fileName[10];
 
    memset(fileName, 0, sizeof(fileName));
    printf("파일 이름 입력 : ");
    scanf("%s", &fileName);
 
    int chkResult = 0;
    int existYn = access(fileName, 0);
 
    if (existYn != 0) {
        printf("해당 파일이 없습니다.");
        return 0;
    }
    else {
        chkResult = AnagramCheck(fileName);
 
        if (chkResult == 0) {
            printf("A valid anagram!\n");
        }
        else if (chkResult == -1) {
            printf("Error: Not a valid anagram.\n");
        }
        else {
            printf("Error: The length of the two strings is different.\n");
        }
    }
 
    return 0;
}
 
int AnagramCheck(char* fileName) {
    FILE* file = NULL;
    int line = 1;
    char str1[STR_LENGTH], str2[STR_LENGTH] = { 0, };
    int arr1[STR_LENGTH] = { 0, };
    int arr2[STR_LENGTH] = { 0, };
    int j = 0;
 
    file = fopen(fileName, "r");
    while (!feof(file)) {
        if (line == 1) fgets(str1, STR_LENGTH, file);
        else fgets(str2, STR_LENGTH, file);
        line++;
    }
 
    int i;
    for (i = 0; i < strlen(str1); i++) {
        if (str1[i] >= 'A' && str1[i] <= 'Z') {
            str1[i] = str1[i] + 32;
            j = str1[i];
            arr1[j]++;
        }
        else {
            if ((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= '0' && str1[i] <= '9')) {
                j = str1[i];
                arr1[j]++;
            }
        }
    }
 
    j = 0;
    for (i = 0; i < strlen(str2); i++) {
        if (str2[i] >= 'A' && str2[i] <= 'Z') {
            str2[i] = str2[i] + 32;
            j = str2[i];
            arr2[j]++;
        }
        else {
            if ((str2[i] >= 'a' && str2[i] <= 'z') || (str2[i] >= '0' && str2[i] <= '9')) {
                j = str2[i];
                arr2[j]++;
            }
        }
    }
 
    int check = 0;
    int str1len = 0, str2len = 0;
 
    for (i = 0; i < STR_LENGTH; i++) {
        if (arr1[i] > 0) str1len += arr1[i];
        if (arr2[i] > 0) str2len += arr2[i];
    }
 
    if (str1len != str2len) {
        check = 1;
    }
    else {
        for (i = 0; i < STR_LENGTH; i++) {
            if (arr1[i] > 0 && arr2[i] > 0) {
                if (arr1[i] == arr2[i]) break;
                else {
                    check = -1;
                    break;
                }
            }
        }
    }
 
    fclose(file);
    return check;
}