Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

64 строки
1.4 KiB
C++

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
bool is_valid_filename(const char* filename) {
const char* invalid_chars = "*<>?|";
if (strpbrk(filename, invalid_chars)) return false;
const char* colon = strchr(filename, ':');
if (colon && (colon != filename + 1 || !isalpha(filename[0]) || colon[1] != '\n')) return false;
const char* ext = strrchr(filename, '.');
if (ext && strcasecmp(ext, ".txt") != 0) return false;
return true;
}
void add_txt_extension(char* filename) {
strcat(filename, ".txt");
}
int main() {
char filename[256];
cout << "Enter filename: ";
cin >> filename;
if (!is_valid_filename(filename)) {
cout << "Invalid filename." << endl;
return 1;
}
if (!strrchr(filename, '.')) add_txt_extension(filename);
ifstream file(filename, ios::binary | ios::ate);
if (!file.is_open()) {
cout << "Failed to open file." << endl;
return 1;
}
streamsize size = file.tellg();
file.seekg(0, ios::beg);
char* buffer = new char[size];
file.read(buffer, size);
char search[256];
cout << "Enter string to search: ";
cin >> search;
size_t count = 0;
char* pos = buffer;
while ((pos = strstr(pos, search))) {
++count;
pos += strlen(search);
}
cout << "Occurrences: " << count << endl;
delete[] buffer;
return 0;
}