#include #include #include #include using namespace std; // Функция для проверки корректности имени файла bool is_valid_filename(const char* filename) { const char* invalid_chars = "\"<>|"; const size_t filename_length = strlen(filename); // Проверка на наличие запрещенных символов if (strpbrk(filename, invalid_chars) != nullptr) { return false; } // Проверка правильности использования двоеточия const char* colon = strchr(filename, ':'); if (colon != nullptr) { if (colon != filename + 1 || !isalpha(filename[0]) || colon[1] != '\\') { return false; } } // Проверка расширения файла const char* extension = strrchr(filename, '.'); if (extension != nullptr) { if (strcmp(extension, ".txt") != 0 && strcmp(extension, ".TXT") != 0) { return false; } } return true; } int main() { char filename[256]; // Запрос имени файла у пользователя cout << "Enter the file name: "; cin.getline(filename, sizeof(filename)); // Проверка корректности имени файла if (!is_valid_filename(filename)) { cout << "Invalid file name!" << endl; return 1; } // Добавление расширения .txt, если его нет if (strrchr(filename, '.') == nullptr) { strcat(filename, ".txt"); } // Открытие файла для чтения ifstream file(filename, ios::binary); if (!file) { cout << "Failed to open the file!" << endl; return 1; } // Определение размера файла file.seekg(0, ios::end); streamsize file_size = file.tellg(); file.seekg(0, ios::beg); // Выделение памяти для хранения содержимого файла char* file_content = new char[file_size]; // Чтение содержимого файла в память file.read(file_content, file_size); file.close(); // Запрос строки у пользователя char search_string[256]; cout << "Enter the search string: "; cin.getline(search_string, sizeof(search_string)); // Подсчет количества вхождений строки в текст файла size_t count = 0; const char* match = strstr(file_content, search_string); while (match != nullptr) { count++; match = strstr(match + 1, search_string); } // Вывод результата cout << "Number of occurrences: " << count << endl; // Освобождение выделенной памяти delete[] file_content; return 0; }