Загрузил(а) файлы в ''

master
RozhinIV 3 месяцев назад
Родитель 3fd9384c3e
Сommit 59e94112ca

@ -0,0 +1,85 @@
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <clocale>
const size_t MAX_SIZE = 256;
bool isValidFileName(const char* fileName) {
const char* forbiddenChars = "*\"<>?|";
if (strpbrk(fileName, forbiddenChars)) {
return false;
}
const char* colon = strchr(fileName, ':');
if (colon) {
if (colon != fileName + 1 || !isalpha(fileName[0])) {
return false;
}
if (*(colon + 1) != '\\') {
return false;
}
}
const char* ext = strrchr(fileName, '.');
if (ext && _stricmp(ext, ".txt") != 0) {
return false;
}
return true;
}
int countOccurrences(const char* text, const char* searchStr) {
int count = 0;
const char* p = text;
while ((p = strstr(p, searchStr)) != nullptr) {
count++;
p += strlen(searchStr);
}
return count;
}
int main() {
setlocale(LC_ALL, "Russian");
char fileName[MAX_SIZE];
std::cout << "Введите имя файла: ";
std::cin.getline(fileName, MAX_SIZE);
while (!isValidFileName(fileName)) {
std::cout << "Некорректное имя файла. Введите заново: ";
std::cin.getline(fileName, MAX_SIZE);
}
if (!strrchr(fileName, '.')) {
strcat_s(fileName, MAX_SIZE, ".txt");
}
std::ifstream file(fileName, std::ios::in | std::ios::binary);
if (!file) {
std::cerr << "Не удалось открыть файл!" << std::endl;
return 1;
}
file.seekg(0, std::ios::end);
size_t fileSize = file.tellg();
file.seekg(0, std::ios::beg);
char* content = new char[fileSize + 1];
file.read(content, fileSize);
content[fileSize] = '\0';
file.close();
char searchStr[MAX_SIZE];
std::cout << "Введите строку для поиска: ";
std::cin.getline(searchStr, MAX_SIZE);
int occurrences = countOccurrences(content, searchStr);
std::cout << "Строка '" << searchStr << "' встречается " << occurrences << " раз(а) в файле." << std::endl;
delete[] content;
return 0;
}
Загрузка…
Отмена
Сохранить