main
TimofeevAnM 3 месяцев назад
Родитель ece2303537
Сommit fcfe4ef65a

@ -0,0 +1,122 @@
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <cstdlib>
const size_t MAX_SIZE = 256;
const char* separators = " \r\n,.!?:;()-";
bool isValidFileName(char* filename) {
// Проверка на запрещенные символы
const char* forbiddenChars = "*\"<>?|";
if (strpbrk(filename, forbiddenChars) != nullptr) {
return false;
}
// Проверка на двоеточие
const char* colon = strchr(filename, ':');
if (colon) {
if (colon != filename + 1 || !isalpha(*(colon - 1)) || *(colon + 1) != '\\') {
return false;
}
}
// Проверка на расширение .txt
const char* dot = strrchr(filename, '.');
if (dot) {
if (strcasecmp(dot, ".txt") != 0) {
return false;
}
} else {
// Если нет расширения, добавить .txt
strcat(filename, ".txt");
}
return true;
}
void loadFileContent(const char* filename, char*& content, size_t& size) {
std::ifstream file(filename, std::ios::binary);
if (!file) {
std::cerr << "Error opening file: " << filename << std::endl;
exit(1);
}
// Перемещение в конец файла для получения размера
file.seekg(0, std::ios::end);
size = file.tellg();
file.seekg(0, std::ios::beg);
// Выделение памяти для содержимого файла
content = new char[size + 1]; // +1 для завершающего '\0'
file.read(content, size);
content[size] = '\0'; // Завершение строки
}
void printWords(const char* text) {
const char* start = text;
while (true) {
const size_t separator_count = strspn(start, separators);
start += separator_count;
if (start[0] == '\0') {
break;
}
const size_t word_length = strcspn(start, separators);
std::cout.write(start, word_length);
std::cout << '\n';
start += word_length;
}
}
int countOccurrences(const char* content, const char* searchStr) {
int count = 0;
const char* tmp = content;
while ((tmp = strstr(tmp, searchStr)) != nullptr) {
count++;
tmp++; // Продолжаем поиск с следующего символа
}
return count;
}
int main() {
char filename[MAX_SIZE];
// 4.1 Запрос имени файла
std::cout << "Enter file name: ";
std::cin.getline(filename, MAX_SIZE);
// 4.2 Проверка имени файла
if (!isValidFileName(filename)) {
std::cerr << "Incorrect file name." << std::endl;
return 1;
}
char* fileContent = nullptr;
size_t fileSize = 0;
// 4.4 Загрузка содержимого файла
loadFileContent(filename, fileContent, fileSize);
// 4.5 Печать слов
printWords(fileContent);
// 4.6 Запрос строки для поиска
char searchStr[MAX_SIZE];
std::cout << "Enter a search string: ";
std::cin.getline(searchStr, MAX_SIZE);
// Подсчет вхождений строки в содержимом файла
int occurrences = countOccurrences(fileContent, searchStr);
std::cout << "Number of occurrences of string \"" << searchStr << "\": " << occurrences << std::endl;
// Освобождение памяти
delete[] fileContent;
return 0;
}
Загрузка…
Отмена
Сохранить