Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

Проверь код на ошибки dir. Так же измени что бы база данных вируса считывалась не txt а…

  1. User

    Проверь код на ошибки dir. Так же измени что бы база данных вируса считывалась не txt а cav.

    #include #include #include <dirent.h> #include #include #include #include #include #include <openssl/md5.h> #include

    using namespace std;

    bool isVirus(string fileName, map<string, string>& virusDatabase) { // Открываем файл и считываем его содержимое в буфер ifstream file(fileName, ios::binary); string buffer((istreambuf_iterator(file)), istreambuf_iterator());

    // Вычисляем хеш-сумму файла
    unsigned char digest[MD5_DIGEST_LENGTH];
    MD5((unsigned char*)buffer.c_str(), buffer.size(), digest);
    char md5sum[33];
    for (int i = 0; i < 16; i++)
        sprintf(&md5sum[i2], " % 02x", (unsigned int)digest[i]);
    
    // Сравниваем хеш-сумму с базой данных вирусов
    if (virusDatabase.count(md5sum) == 1) {
        return true;
    }
    
    return false;
    

    }

    bool deleteFile(string fileName) { if (remove(fileName.c_str()) != 0) { return false; }

    return true;
    

    }

    vector getFilesInDirectory(string path) { vector files;

    DIR dir;
    struct dirent* ent;
    if ((dir = opendir(path.c_str())) != NULL) {
        while ((ent = readdir(dir)) != NULL) {
            if (ent->d_type == DT_REG) { // Только обычные файлы
                files.push_back(ent->d_name);
            }
        }
        closedir(dir);
    }
    
    return files;
    

    }

    void scanDirectory(string path, map<string, string>& virusDatabase, bool deleteVirus) { vector files = getFilesInDirectory(path);

    for (string fileName : files) {
        string fullFilePath = path + " / " + fileName;
    
        if (isVirus(fullFilePath, virusDatabase)) {
            cout << "Файл " << fullFilePath << " является вирусом!" << endl;
            // Предлагаем удалить файл
            if (deleteVirus)
                deleteFile(fullFilePath);
        }
    }
    
    // Рекурсивный вызов для всех поддиректорий
    DIR* dir;
    struct dirent* ent;
    if ((dir = opendir(path.c_str())) != NULL) {
        while ((ent = readdir(dir)) != NULL) {
            if (ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "…") != 0) { // Только директории, кроме . и …
                string subDirPath = path + " / " + ent->d_name;
                scanDirectory(subDirPath, virusDatabase, deleteVirus);
            }
        }
        closedir(dir);
    }
    

    }

    void scanDirectoryThread(string path, map<string, string>& virusDatabase, bool deleteVirus) { cout << "Начало сканирования директории: " << path << endl; auto start = chrono::high_resolution_clock::now(); scanDirectory(path, virusDatabase, deleteVirus); auto end = chrono::high_resolution_clock::now(); double elapsedTimeInSeconds = chrono::duration(end - start).count(); cout << "Окончание сканирования директории: " << path << endl; cout << "Время выполнения : " << elapsedTimeInSeconds << " секунд" << endl; }

    void loadVirusDatabase(string databaseFilePath, map<string, string>& virusDatabase) { // Получаем список вирусов из базы данных ifstream databaseFile(databaseFilePath); string line; while (getline(databaseFile, line)) { // Вычисляем хеш-сумму вируса unsigned char digest[MD5_DIGEST_LENGTH]; MD5((unsigned char*)line.c_str(), line.length(), digest); char md5sum[33]; for (int i = 0; i < 16; i++) sprintf(&md5sum[i * 2], " % 02x", (unsigned int)digest[i]);

        virusDatabase.insert(pair<string, string>(md5sum, line));
    }
    

    }

    int main() { // Путь к директории, которую нужно просканировать string path = " / path / to / my / directory";

    // Путь к файлу базы данных вирусов
    string databaseFilePath = " / path / to / my / database.txt";
    
    // Загружаем базу данных вирусов
    map<string, string> virusDatabase;
    loadVirusDatabase(databaseFilePath, virusDatabase);
    
    // По умолчанию антивирус включен
    bool antivirusEnabled = true;
    
    // Меню программы
    while (true) {
        cout << "1.Сканирование директории" << endl;
        cout << "2.Включение / выключение антивируса" << endl;
        cout << "3.Выход" << endl;
    
        int choice;
        cin >> choice;
    
        switch (choice) {
        case 1:
            if (antivirusEnabled) {
                // Сканируем директорию на наличие вирусов с помощью нескольких потоков
                const int numThreads = 4;
                bool deleteVirus = true;
                thread threads[numThreads];
                for (int i = 0; i < numThreads; i++) {
                    threads[i] = thread(scanDirectoryThread, path, virusDatabase, deleteVirus);
                }
                for (int i = 0; i < numThreads; i++) {
                    threads[i].join();
                }
            }
            else {
                cout << "Антивирус выключен!Включите антивирус, чтобы выполнить сканирование директории." << endl;
            }
            break;
        case 2:
            antivirusEnabled = !antivirusEnabled;
            if (antivirusEnabled) {
                cout << "Антивирус включен!" << endl;
            }
            else {
                cout << "Антивирус выключен!" << endl;
            }
            break;
        case 3:
            return 0;
        default:
            cout << "Неправильный ввод!" << endl;
        }
    }
    
    return 0;
    

    }

  2. Assistant

    Ошибок в коде dir не обнаружено.

    Чтобы изменить, чтобы база данных вирусов считывалась не из txt, а из cav файлов, нужно изменить следующую строку:

    string databaseFilePath = " / path / to / my / database.txt";
    

    на

    string databaseFilePath = " / path / to / my / database.cav";
    

    также нужно убедиться, что файл базы данных вирусов действительно имеет расширение "cav".

  3. User

    как или где найти базы данных вирусов

  4. Assistant

    Существует множество источников для загрузки баз данных вирусов. Некоторые из них бесплатны, другие платные.

    Ниже приведены некоторые из бесплатных баз данных вирусов:

    Важно заметить, что базы данных вирусов должны быть обновлены регулярно, чтобы защитить ваш компьютер от новых угроз.