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

66 строки
1.6 KiB
C++

#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
char filename[256];
cout << "Enter file name: ";
cin.getline(filename, sizeof(filename));
bool isValid = true;
const char* forbiddenChars = "*\"<>?|";
if (strpbrk(filename, forbiddenChars) != 0)
isValid = false;
if (strchr(filename, ':') != nullptr &&
(filename[1] != '\\' || !isalpha(filename[0]) ||
strchr(filename, '\\') != strrchr(filename, '\\')))
isValid = false;
if (strchr(filename, '.') == NULL) {
strcat(filename, ".txt");
}
if (isValid)
{
ifstream file(filename, ios::binary | ios::ate);
if (file.is_open())
{
streampos fileSize = file.tellg();
char* buffer = new char[fileSize];
file.seekg(0, ios::beg);
file.read(buffer, fileSize);
file.close();
char searchString[256];
cout << "Enter a search string: ";
cin.getline(searchString, sizeof(searchString));
int count = 0;
char* p = buffer;
while ((p = strstr(p, searchString)) != nullptr)
{
count++;
p += strlen(searchString);
}
cout << "Number of occurrences of a string \"" << searchString << "\" in a text file: " << count << endl;
delete[] buffer;
}
else
cout << "Error opening file." << endl;
}
else
cout << "Invalid file name." << endl;
system("pause");
return 0;
}