diff --git a/task_4 b/task_4 new file mode 100644 index 0000000..4fe2a89 --- /dev/null +++ b/task_4 @@ -0,0 +1,127 @@ +#include +#include +#include +#include + +using namespace std; + +const size_t MAX_FILENAME_LENGTH = 260; + +const size_t MAX_SEARCH_STRING_LENGTH = 256; + +const char* forbidden_chars = "*"<>?|"; + +bool isValidFilename(const char* filename) { +for (size_t i = 0; i < strlen(forbidden_chars); ++i) { +if (strchr(filename, forbidden_chars[i]) != nullptr) { +return false; +} +} + +const char* colon = strchr(filename, ':'); +if (colon != nullptr) { + if (colon - filename != 1) { + return false; + } + if (!isalpha(filename[0])) { + return false; + } + if (*(colon + 1) != '\\') { + return false; + } +} + +const char* dot = strrchr(filename, '.'); +if (dot != nullptr) { + if (strlen(dot) != 4) { + return false; + } + char ext[5]; + strncpy(ext, dot, 4); + ext[4] = '\0'; + for (int i = 0; i < 4; ++i) { + ext[i] = tolower(ext[i]); + } + if (strcmp(ext, ".txt") != 0) { + return false; + } +} +return true; +} +void addTxtExtension(char* filename) { +if (strrchr(filename, '.') == nullptr) { +strcat(filename, ".txt"); +} +} + +int main() { + +char filename[MAX_FILENAME_LENGTH]; +cout << "Введите имя файла: "; +cin.getline(filename, MAX_FILENAME_LENGTH); +if (!isValidFilename(filename)) { + cout << "Некорректное имя файла." << endl; + return 1; +} +if (!isValidFilename(filename)) { + cout << "Некорректное имя файла после добавления расширения." << endl; + return 1; +} + +FILE* file = fopen(filename, "rb"); +if (file == nullptr) { + cout << "Не удалось открыть файл: " << filename << endl; + return 1; +} + +long file_size = ftell(file); +if (file_size == -1L) { + cout << "Не удалось определить размер файла." << endl; + fclose(file); + return 1; +} +rewind(file); +char* file_content = (char*)malloc(file_size + 1); +if (file_content == nullptr) { + cout << "Не удалось выделить память для содержимого файла." << endl; + fclose(file); + return 1; +} + +size_t read_size = fread(file_content, sizeof(char), file_size, file); +if (read_size != (size_t)file_size) { + cout << "Ошибка при чтении файла." << endl; + free(file_content); + fclose(file); + return 1; +} + +file_content[file_size] = '\0'; + +fclose(file); + +char search_string[MAX_SEARCH_STRING_LENGTH]; +cout << "Введите строку для поиска: "; +cin.getline(search_string, MAX_SEARCH_STRING_LENGTH); + +int count = 0; +char* pos = file_content; + +size_t search_len = strlen(search_string); +if (search_len == 0) { + cout << "Пустая строка для поиска." << endl; + free(file_content); + return 1; +} + +while ((pos = strstr(pos, search_string)) != nullptr) { + count++; + pos += search_len; +} +cout << "Число вхождений строки \"" << search_string << "\": " << count << endl; + + +free(file_content); + +return 0; +} \ No newline at end of file