#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>

bool is_valid_filename(const char* filename) {
    // Проверка на запрещенные символы
    if (strpbrk(filename, "*\"<>?|")) return false;

    // Проверка двоеточие
    const char* colon = strchr(filename, ':');
    if (colon != nullptr) {
        if (colon != filename + 1 || !isalpha(filename[0]) || colon[1] != '\\') return false;
    }

    // Проверка расширения 
    const char* dot = strrchr(filename, '.');
    if (dot != nullptr) {
        if (_stricmp(dot, ".txt") != 0) return false;
    }

    return true;
}

int count_occurrences(const char* text, const char* substring) {
    int count = 0;
    const char* temp = text;
    while ((temp = strstr(temp, substring)) != nullptr) {
        ++count;
        ++temp;
    }
    return count;
}

int main() {
    char filename[260];
    std::cout << "Enter filename: ";
    std::cin.getline(filename, 260);

    if (!is_valid_filename(filename)) {
        std::cerr << "Invalid filename.\n";
        return 1;
    }

    if (strrchr(filename, '.') == nullptr) {
        strcat_s(filename, sizeof(filename), ".txt");
    }

    std::ifstream file(filename, std::ifstream::binary);
    if (!file) {
        std::cerr << "Failed to open file.\n";
        return 1;
    }

    file.seekg(0, std::ifstream::end);
    long size = file.tellg();
    file.seekg(0, std::ifstream::beg);

    char* buffer = new char[size + 1];
    file.read(buffer, size);

    buffer[size] = '\0'; 

    
    for (long i = 0; i < size; ++i) {
        if (buffer[i] == '\r' && buffer[i + 1] == '\n') {
            buffer[i] = '\n';
            std::memmove(&buffer[i + 1], &buffer[i + 2], size - i - 1);
            size--;
        }
    }

    char search_string[100];
    std::cout << "Enter string to search: ";
    std::cin.getline(search_string, 100);

    int occurrences = count_occurrences(buffer, search_string);
    std::cout << "Occurrences of '" << search_string << "': " << occurrences << "\n";

    delete[] buffer;
    return 0;
}
