Console Interactive File Manager for Protected Files on Windows

Joined
Jun 12, 2020
Messages
60
Reaction score
3
This C++ program is an interactive file manager for protected files on Windows that utilizes the SeBackupPrivilege administrative privilege to access system or locked files. It implements a command-line interface with a menu that allows users to create files with security descriptors limited to administrators, write, read, replace content, view detailed information (size, dates, attributes—though displaying attributes is not yet functional), or delete these protected files. It leverages the advanced Windows API using RAII classes like SafeHandle and TokenManager for automatic and secure management of handles and privileges, ensuring proper resource cleanup even in case of errors, and requires running as an administrator to function correctly.

C++:
/*


MIT License


Copyright (c) 2025 CoTon_TiGe_MoUaRf



Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:



The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.




THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


*/
#include <windows.h>

#include <sddl.h>

#include <aclapi.h>

#include <iostream>

#include <string>

#include <cstring>

#include <vector>

#include <limits>

#include <iomanip>

#include <memory>

#include <stdexcept>


#pragma comment(lib, "advapi32.lib")


using namespace std;
#define SE_BACKUP_NAME_A "SeBackupPrivilege"

// ============================================

// RAII Wrapper pour les handles Windows

// ============================================

class SafeHandle {

private:

    HANDLE m_handle;


    SafeHandle(const SafeHandle&) = delete;

    SafeHandle& operator=(const SafeHandle&) = delete;


public:

    explicit SafeHandle(HANDLE handle = NULL) noexcept : m_handle(handle) {}

 

    SafeHandle(SafeHandle&& other) noexcept : m_handle(other.release()) {}

    SafeHandle& operator=(SafeHandle&& other) noexcept {

        reset(other.release());

        return *this;

    }


    ~SafeHandle() noexcept {

        if (m_handle != NULL && m_handle != INVALID_HANDLE_VALUE) {

            CloseHandle(m_handle);

        }

    }


    HANDLE get() const noexcept { return m_handle; }

    HANDLE* addressof() noexcept { return &m_handle; }

    bool isValid() const noexcept {

        return m_handle != NULL && m_handle != INVALID_HANDLE_VALUE;

    }


    HANDLE release() noexcept {

        HANDLE temp = m_handle;

        m_handle = NULL;

        return temp;

    }


    void reset(HANDLE handle = NULL) noexcept {

        if (m_handle != NULL && m_handle != INVALID_HANDLE_VALUE) {

            CloseHandle(m_handle);

        }

        m_handle = handle;

    }


    explicit operator bool() const noexcept { return isValid(); }

};


// ============================================

// TokenManager RAII - Gestion complète des tokens

// ============================================

class TokenManager {

private:

    SafeHandle m_tokenHandle;

    DWORD m_processId;

    bool m_backupPrivilegeEnabled = false;


    void throwIfInvalid() const {

        if (!m_tokenHandle.isValid()) {

            throw runtime_error("Token handle is invalid");

        }

    }


    string GetErrorMessage(const string& functionName, DWORD dwError) {

        LPVOID lpMsgBuf;

        FormatMessageA(

            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,

            NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),

            (LPSTR)&lpMsgBuf, 0, NULL

        );

        string errorMsg = "Erreur dans " + functionName + " (Code: " + to_string(dwError) + "): " + (LPSTR)lpMsgBuf;

        LocalFree(lpMsgBuf);

        return errorMsg;

    }


public:

    explicit TokenManager(DWORD processId = GetCurrentProcessId()) : m_processId(processId) {

        HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId);

        if (!processHandle) {

            throw runtime_error("Failed to open process: " + to_string(GetLastError()));

        }

        SafeHandle procGuard(processHandle);


        HANDLE tokenHandle = NULL;

        if (!OpenProcessToken(processHandle, TOKEN_DUPLICATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tokenHandle)) {

            throw runtime_error("Failed to open process token: " + to_string(GetLastError()));

        }

        m_tokenHandle.reset(tokenHandle);

    }


    TokenManager(const TokenManager&) = delete;

    TokenManager& operator=(const TokenManager&) = delete;


    TokenManager(TokenManager&&) = default;

    TokenManager& operator=(TokenManager&&) = default;


    bool enableBackupPrivilege() {

        throwIfInvalid();

        cout << "  [PRIVILÈGE] Activation de SeBackupPrivilege..." << endl;

  

        if (m_backupPrivilegeEnabled) return true;

  

        LUID privilegeLuid;

        if (!LookupPrivilegeValueA(NULL, SE_BACKUP_NAME_A, &privilegeLuid)) {

            DWORD error = GetLastError();

            cerr << " LookupPrivilegeValueA failed (Code: " << error << "): "

                 << GetErrorMessage("LookupPrivilegeValueA", error) << endl;

            return false;

        }


        TOKEN_PRIVILEGES tokenPrivileges = {};

        tokenPrivileges.PrivilegeCount = 1;

        tokenPrivileges.Privileges[0].Luid = privilegeLuid;

        tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;


        if (!AdjustTokenPrivileges(m_tokenHandle.get(), FALSE, &tokenPrivileges, 0, NULL, NULL)) {

            DWORD error = GetLastError();

            if (error == ERROR_NOT_ALL_ASSIGNED) {

                cout << "  Le token n'a pas le privilège SeBackupPrivilege" << endl;

            } else {

                cerr << " AdjustTokenPrivileges failed: " << GetErrorMessage("AdjustTokenPrivileges", error) << endl;

            }

            return false;

        }


        m_backupPrivilegeEnabled = true;

        cout << "   SeBackupPrivilege activé" << endl;

        return true;

    }




    void disableBackupPrivilege() {

        if (m_backupPrivilegeEnabled) {

            LUID privilegeLuid;

            if (LookupPrivilegeValueA(NULL, SE_BACKUP_NAME_A, &privilegeLuid)) {

                TOKEN_PRIVILEGES tokenPrivileges = {};

                tokenPrivileges.PrivilegeCount = 1;

                tokenPrivileges.Privileges[0].Luid = privilegeLuid;

                tokenPrivileges.Privileges[0].Attributes = 0;

                AdjustTokenPrivileges(m_tokenHandle.get(), FALSE, &tokenPrivileges, 0, NULL, NULL);

            }

            m_backupPrivilegeEnabled = false;

            cout << "   SeBackupPrivilege désactivé" << endl;

        }

    }


    ~TokenManager() {

        disableBackupPrivilege();  // Maintenant déclaré !

    }


    HANDLE getHandle() const noexcept { return m_tokenHandle.get(); }

};


// ============================================

// ProtectedFileManager - Version RAII complète

// ============================================

class ProtectedFileManager {

private:

    TokenManager m_tokenManager;

    string lastErrorMessage;

    DWORD lastErrorCode;


    string GetErrorMessage(const string& functionName, DWORD dwError) {

        LPVOID lpMsgBuf;

        FormatMessageA(

            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,

            NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),

            (LPSTR)&lpMsgBuf, 0, NULL

        );

        string errorMsg = "Erreur dans " + functionName + " (Code: " + to_string(dwError) + "): " + (LPSTR)lpMsgBuf;

        LocalFree(lpMsgBuf);

        return errorMsg;

    }


    void LogError(const string& functionName, DWORD dwError) {

        lastErrorCode = dwError;

        lastErrorMessage = GetErrorMessage(functionName, dwError);

        cerr << "Erreur " << lastErrorMessage << endl;

    }


    bool CreateSecurityDescriptor(PSECURITY_DESCRIPTOR* ppSD, PACL* ppACL, PSID* ppAdminSID) {

        DWORD dwRes = 0;

        EXPLICIT_ACCESS ea[1];

        SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;


        cout << "  [1/5] Création du SID administrateur..." << endl;

        if (!AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,

    DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ppAdminSID)) {

    DWORD sidError = ::GetLastError();  // Capture d'abord

    LogError("AllocateAndInitializeSid", sidError);

    return false;

}

        cout << "   SID administrateur créé" << endl;


        ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));

        ea[0].grfAccessPermissions = FILE_ALL_ACCESS;

        ea[0].grfAccessMode = SET_ACCESS;

        ea[0].grfInheritance = NO_INHERITANCE;

        ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;

        ea[0].Trustee.TrusteeType = TRUSTEE_IS_GROUP;

        ea[0].Trustee.ptstrName = (LPSTR)*ppAdminSID;


        cout << "  [3/5] Création de l'ACL..." << endl;

        dwRes = SetEntriesInAclA(1, ea, NULL, ppACL);

        if (ERROR_SUCCESS != dwRes) {

            LogError("SetEntriesInAcl", dwRes);

            FreeSid(*ppAdminSID);

            return false;

        }

        cout << "   ACL créée avec succès" << endl;


        *ppSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);

        if (NULL == *ppSD) {

            LogError("LocalAlloc", ::GetLastError());

            LocalFree(*ppACL);

            FreeSid(*ppAdminSID);

            return false;

        }


        if (!InitializeSecurityDescriptor(*ppSD, SECURITY_DESCRIPTOR_REVISION)) {

            LogError("InitializeSecurityDescriptor", ::GetLastError());

            LocalFree(*ppSD);

            LocalFree(*ppACL);

            FreeSid(*ppAdminSID);

            return false;

        }


        if (!SetSecurityDescriptorDacl(*ppSD, TRUE, *ppACL, FALSE)) {

            LogError("SetSecurityDescriptorDacl", ::GetLastError());

            LocalFree(*ppSD);

            LocalFree(*ppACL);

            FreeSid(*ppAdminSID);

            return false;

        }

        cout << "   Descripteur de sécurité configuré" << endl;

        return true;

    }


    bool CreateParentDirectory(const string& filePath) {

        size_t lastSlash = filePath.find_last_of("\\/");

        if (lastSlash == string::npos) return true;


        string dirPath = filePath.substr(0, lastSlash);

        if (!CreateDirectoryA(dirPath.c_str(), NULL)) {

            DWORD error = ::GetLastError();

            if (error != ERROR_ALREADY_EXISTS) {

                LogError("CreateDirectoryA", error);

                return false;

            }

        }

        return true;

    }


    void FreeSecurityResources(PSECURITY_DESCRIPTOR pSD, PACL pACL, PSID pAdminSID) {

        if (pAdminSID) FreeSid(pAdminSID);

        if (pACL) LocalFree(pACL);

        if (pSD) LocalFree(pSD);

    }


public:

    ProtectedFileManager() : m_tokenManager(), lastErrorCode(0), lastErrorMessage("") {}


    bool Initialize() {

        cout << " Vérification des privilèges administrateur..." << endl;

        return m_tokenManager.enableBackupPrivilege();

    }


    bool CreateProtectedFile(const string& filePath) {

        cout << "\n  CRÉATION DE FICHIER PROTÉGÉ AVEC SeBackupPrivilege      " << endl;


        PSID pAdminSID = NULL;

        PACL pACL = NULL;

        PSECURITY_DESCRIPTOR pSD = NULL;

        SECURITY_ATTRIBUTES sa;

        bool bSuccess = false;


        cout << "\nÉtape 1: Configuration de la sécurité" << endl;

        if (!CreateSecurityDescriptor(&pSD, &pACL, &pAdminSID)) {

            return false;

        }


        cout << "\nÉtape 2: Création du répertoire parent" << endl;

        if (!CreateParentDirectory(filePath)) {

            FreeSecurityResources(pSD, pACL, pAdminSID);

            return false;

        }

        cout << "   Répertoire parent créé ou existant" << endl;


        cout << "\nÉtape 3: Création du fichier protégé" << endl;

        sa.nLength = sizeof(SECURITY_ATTRIBUTES);

        sa.lpSecurityDescriptor = pSD;

        sa.bInheritHandle = FALSE;


        SafeHandle hFile(CreateFileA(

            filePath.c_str(),

            GENERIC_READ | GENERIC_WRITE,

            0,

            &sa,

            CREATE_ALWAYS,

            FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,

            NULL

        ));


        if (!hFile) {

            LogError("CreateFileA (avec backup)", ::GetLastError());

        } else {

            cout << "   Fichier créé avec succès: " << filePath << endl;

            cout << "   Droits administrateur appliqués" << endl;

            bSuccess = true;

        }


        FreeSecurityResources(pSD, pACL, pAdminSID);

        return bSuccess;

    }


    bool WriteToFile(const string& filePath, const string& content) {

        cout << "\n  ÉCRITURE DANS LE FICHIER PROTÉGÉ (SeBackupPrivilege)       " << endl;


        SafeHandle hFile(CreateFileA(

            filePath.c_str(),

            GENERIC_WRITE,

            FILE_SHARE_READ,

            NULL,

            OPEN_EXISTING,

            FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,

            NULL

        ));


        if (!hFile) {

            LogError("CreateFileA (écriture backup)", ::GetLastError());

            return false;

        }


        cout << "   Fichier ouvert avec succès" << endl;


        DWORD writtenBytes = 0;

        if (!WriteFile(hFile.get(), content.c_str(), (DWORD)content.length(), &writtenBytes, NULL)) {

            LogError("WriteFile", ::GetLastError());

            return false;

        }


        cout << "   Écriture réussie: " << writtenBytes << " octets écrits" << endl;

        return true;

    }


    bool ReadFromFile(const string& filePath, string& outContent) {

        cout << "\n  LECTURE DU FICHIER PROTÉGÉ (SeBackupPrivilege)             " << endl;


        SafeHandle hFile(CreateFileA(

            filePath.c_str(),

            GENERIC_READ,

            FILE_SHARE_READ,

            NULL,

            OPEN_EXISTING,

            FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,

            NULL

        ));


        if (!hFile) {

            LogError("CreateFileA (lecture backup)", ::GetLastError());

            return false;

        }


        cout << "   Fichier ouvert avec succès" << endl;


        char buffer[4096];

        DWORD readBytes = 0;

        outContent.clear();


        do {

            if (!ReadFile(hFile.get(), buffer, sizeof(buffer) - 1, &readBytes, NULL)) {

                LogError("ReadFile", ::GetLastError());

                return false;

            }

            if (readBytes > 0) {

                buffer[readBytes] = '\0';

                outContent += buffer;

            }

        } while (readBytes == sizeof(buffer) - 1);


        cout << "   Lecture réussie: " << outContent.length() << " octets lus" << endl;

        return true;

    }


    bool DisplayFileContent(const string& filePath) {

        string content;

        if (!ReadFromFile(filePath, content)) {

            return false;

        }


        cout << "\nÉtape 3: Affichage du contenu" << endl;

        cout << "----------------------------------------------------------------" << endl;

        cout << content << endl;

        cout << "----------------------------------------------------------------" << endl;

        return true;

    }


    bool DeleteProtectedFile(const string& filePath) {

        cout << "\n  SUPPRESSION DU FICHIER PROTÉGÉ (SeBackupPrivilege)         " << endl;


        bool result = DeleteFileA(filePath.c_str());

        DWORD error = ::GetLastError();


        if (!result) {

            LogError("DeleteFileA (avec backup)", error);

            return false;

        }


        cout << "   Fichier supprimé avec succès: " << filePath << endl;

        return true;

    }


    bool AppendToFile(const string& filePath, const string& content) {

        cout << "\n  AJOUT DE CONTENU AU FICHIER PROTÉGÉ (SeBackupPrivilege)    " << endl;


        SafeHandle hFile(CreateFileA(

            filePath.c_str(),

            FILE_APPEND_DATA | GENERIC_WRITE,

            FILE_SHARE_READ,

            NULL,

            OPEN_EXISTING,

            FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,

            NULL

        ));


        if (!hFile) {

            LogError("CreateFileA (ajout backup)", ::GetLastError());

            return false;

        }


        cout << "   Fichier ouvert avec succès" << endl;


        DWORD writtenBytes = 0;

        if (!WriteFile(hFile.get(), content.c_str(), (DWORD)content.length(), &writtenBytes, NULL)) {

            LogError("WriteFile (ajout)", ::GetLastError());

            return false;

        }


        cout << "   Ajout réussi: " << writtenBytes << " octets ajoutés" << endl;

        return true;

    }


    string GetLastError() const { return lastErrorMessage; }

    DWORD GetLastErrorCode() const { return lastErrorCode; }


    bool FileExists(const string& filePath) {

        DWORD dwAttrib = GetFileAttributesA(filePath.c_str());

        return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));

    }


    long long GetFileSize(const string& filePath) {

        SafeHandle hFile(CreateFileA(

            filePath.c_str(),

            GENERIC_READ,

            FILE_SHARE_READ,

            NULL,

            OPEN_EXISTING,

            FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,

            NULL

        ));


        if (!hFile) {

            LogError("CreateFileA (GetFileSize)", ::GetLastError());

            return -1;

        }


        LARGE_INTEGER fileSize;

        if (!GetFileSizeEx(hFile.get(), &fileSize)) {

            LogError("GetFileSizeEx", ::GetLastError());

            return -1;

        }


        return fileSize.QuadPart;

    }


    void DisplayFileInfo(const string& filePath) {

        cout << "\n  INFORMATIONS DU FICHIER (SeBackupPrivilege)                 " << endl;

        cout << "----------------------------------------------------------------" << endl;


        cout << "Chemin: " << filePath << endl;


        if (!FileExists(filePath)) {

            cout << " Le fichier n'existe pas" << endl;

            return;

        }


        cout << " Le fichier existe" << endl;


        long long fileSize = GetFileSize(filePath);

        if (fileSize >= 0) {

            cout << "Taille: " << fileSize << " octets (" << (fileSize / 1024.0) << " Ko)" << endl;

        }


        WIN32_FILE_ATTRIBUTE_DATA fileInfo;

        if (GetFileAttributesExA(filePath.c_str(), GetFileExInfoStandard, &fileInfo)) {

            SYSTEMTIME stUTC, stLocal;

            FILETIME ftBuf;


            cout << "\nAttributs:" << endl;

            if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {

                cout << "  - Lecture seule" << endl;

            }

            if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {

                cout << "  - Caché" << endl;

            }

            if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
                cout << "  - Fichier système" << endl;

            }


            // Conversion des dates

            FileTimeToLocalFileTime(&fileInfo.ftLastWriteTime, &ftBuf);

            FileTimeToSystemTime(&ftBuf, &stLocal);

      

            cout << "\nDernière modification: ";

            cout << setfill('0') << setw(2) << stLocal.wDay << "/"

                 << setw(2) << stLocal.wMonth << "/"

                 << setw(2) << stLocal.wYear << " "

                 << setw(2) << stLocal.wHour << ":"

                 << setw(2) << stLocal.wMinute << ":"

                 << setw(2) << stLocal.wSecond << endl;

        }

        cout << "----------------------------------------------------------------" << endl;

    }

};


// ============================================

// Fonctions d'interface utilisateur

// ============================================

void DisplayMenu() {

    cout << "\n";

    cout << "         GESTIONNAIRE DE FICHIERS PROTÉGÉS WINDOWS              " << endl;

    cout << "          AVEC SeBackupPrivilege + RAII ACTIVÉ              " << endl;

    cout << "----------------------------------------------------------------" << endl;

    cout << "  1. Créer un fichier protégé                                   " << endl;

    cout << "  2. Écrire dans un fichier                                     " << endl;

    cout << "  3. Lire un fichier                                            " << endl;

    cout << "  4. Ajouter du contenu à un fichier                            " << endl;

    cout << "  5. Afficher les informations du fichier                       " << endl;

    cout << "  6. Supprimer un fichier                                       " << endl;

    cout << "  7. Quitter                                                    " << endl;

    cout << "----------------------------------------------------------------" << endl;

    cout << "\n  IMPORTANT: Exécutez en tant qu'Administrateur !" << endl;

    cout << "Sélectionnez une option (1-7): ";

}


int main() {

    ProtectedFileManager fileManager;


    cout << "----------------------------------------------------------------" << endl;

    cout << "   GESTIONNAIRE DE FICHIERS PROTÉGÉS AVEC SeBackupPrivilege    " << endl;

    cout << "   VERSION RAII - 100% EXCEPTION-SAFE & HANDLE-SAFE       " << endl;

    cout << "   Plateforme: Windows (API Windows + Privilèges Admin)        " << endl;

    cout << "----------------------------------------------------------------" << endl;


    //  VÉRIFICATION CRITIQUE DES PRIVILÈGES AU DÉMARRAGE (RAII)

    try {

        if (!fileManager.Initialize()) {

            cout << "\n ERREUR CRITIQUE: Impossible d'activer SeBackupPrivilege !" << endl;

            cout << "    Exécutez l'application EN TANT QU'ADMINISTRATEUR" << endl;

            cout << "    Clic droit sur l'exécutable → 'Exécuter en tant qu'administrateur'" << endl;

            cout << "----------------------------------------------------------------" << endl;

            system("pause");

            return 1;

        }

        cout << " Initialisation réussie - Privilèges administrateur OK !" << endl;

    } catch (const exception& e) {

        cout << "\n ERREUR FATAL: " << e.what() << endl;

        cout << "    Vérifiez les privilèges administrateur" << endl;

        system("pause");

        return 1;

    }


    int choice = 0;

    string filePath, content;


    while (true) {

        DisplayMenu();

        cin >> choice;

        cin.ignore(numeric_limits<streamsize>::max(), '\n');


        switch (choice) {

            case 1: {

                cout << "\n--- Création de fichier protégé ---" << endl;

                cout << "Entrez le chemin complet du fichier (ex: C:\\test\\protected.txt): ";

                getline(cin, filePath);


                if (fileManager.CreateProtectedFile(filePath)) {

                    cout << "\n Fichier créé avec succès et protégé !" << endl;

                } else {

                    cout << "\n Erreur: " << fileManager.GetLastError() << endl;

                }

                break;

            }


            case 2: {

                cout << "\n--- Écriture dans un fichier ---" << endl;

                cout << "Entrez le chemin du fichier: ";

                getline(cin, filePath);

                cout << "Entrez le contenu à écrire: ";

                getline(cin, content);


                if (fileManager.WriteToFile(filePath, content)) {

                    cout << "\n  Écriture réussie !" << endl;

                } else {

                    cout << "\n  Erreur: " << fileManager.GetLastError() << endl;

                }

                break;

            }


            case 3: {

                cout << "\n--- Lecture d'un fichier ---" << endl;

                cout << "Entrez le chemin du fichier: ";

                getline(cin, filePath);

          

                if (fileManager.DisplayFileContent(filePath)) {

                    cout << "\n Lecture réussie !" << endl;

                } else {

                    cout << "\n  Erreur: " << fileManager.GetLastError() << endl;

                }

                break;

            }


            case 4: {

                cout << "\n--- Ajout de contenu à un fichier ---" << endl;

                cout << "Entrez le chemin du fichier: ";

                getline(cin, filePath);

                cout << "Entrez le contenu à ajouter: ";

                getline(cin, content);


                if (fileManager.AppendToFile(filePath, content)) {

                    cout << "\n Ajout réussi !" << endl;

                } else {

                    cout << "\n Erreur: " << fileManager.GetLastError() << endl;

                }

                break;

            }


            case 5: {

                cout << "\n--- Informations du fichier ---" << endl;

                cout << "Entrez le chemin du fichier: ";

                getline(cin, filePath);


                fileManager.DisplayFileInfo(filePath);

                break;

            }


            case 6: {

                cout << "\n--- Suppression de fichier ---" << endl;

                cout << "Entrez le chemin du fichier: ";

                getline(cin, filePath);


                cout << "\n Êtes-vous sûr de vouloir supprimer '" << filePath << "' ? (o/n): ";

                char confirmation;

                cin >> confirmation;

                cin.ignore(numeric_limits<streamsize>::max(), '\n');


                if (confirmation == 'o' || confirmation == 'O') {

                    if (fileManager.DeleteProtectedFile(filePath)) {

                        cout << "\n Fichier supprimé avec succès !" << endl;

                    } else {

                        cout << "\n Erreur: " << fileManager.GetLastError() << endl;

                    }

                } else {

                    cout << "\n  Suppression annulée" << endl;

                }

                break;

            }


            case 7: {

                cout << "\n----------------------------------------------------------------" << endl;

                cout << "  Merci d'avoir utilisé le gestionnaire de fichiers protégés  " << endl;

                cout << "   SeBackupPrivilege désactivé automatiquement (RAII)         " << endl;

                cout << "   Tous les handles fermés automatiquement (SafeHandle)       " << endl;

                cout << "  Au revoir!                                                    " << endl;

                cout << "----------------------------------------------------------------" << endl;

                return 0;

            }


            default: {

                cout << "\n Option invalide. Veuillez sélectionner une option entre 1 et 7." << endl;

                break;

            }

        }


        cout << "\n\n  Appuyez sur Entrée pour continuer...";

        cin.get();

    }


    return 0;

}
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top