Code Generator | C/C++

Basic Notepad Implementation in Kernel

This document outlines the implementation of a Notepad feature in a C++ Kernel class, allowing users to create, edit, and save text files using standard file I/O and simple user commands.


Empty image or helper icon

Prompt

Write the code for notepad inside the core code of my operating system:
#include 
#include 
#include 
#include 
#include 

namespace fs = std::filesystem;

class Kernel {
public:
    Kernel() {
        currentPath = fs::current_path();
        displayWelcomeMessage();
    }

    void run() {
        std::string command;
        while (true) {
            std::cout << currentPath << "> ";
            std::getline(std::cin, command);
            processCommand(command);
        }
    }

private:
    fs::path currentPath;

    void displayWelcomeMessage() {
        std::cout << "Welcome to BlankOS 1.0!" << std::endl;
        std::cout << "Type 'help' for a list of commands." << std::endl;
    }

    void processCommand(const std::string& command) {
        try {
            if (command == "help") {
                displayHelp();
            } else if (command == "cls") {
                clearScreen();
            } else if (command == "ver") {
                std::cout << "Version 1.0.0" << std::endl;
            } else if (command.substr(0, 3) == "cd ") {
                changeDirectory(command.substr(3));
            } else if (command == "dir") {
                listFiles();
            } else if (command.substr(0, 5) == "ndir ") {
                createDirectory(command.substr(5));
            } else if (command.substr(0, 6) == "ddir ") {
                deleteDirectory(command.substr(6));
            } else if (command.substr(0, 6) == "dfile ") {
                deleteFile(command.substr(6));
            } else if (command.substr(0, 6) == "renfile ") {
                renameFile(command.substr(8));
            } else if (command.substr(0, 8) == "rendir ") {
                renameDirectory(command.substr(8));
            } else if (command == "updir") {
                goUpDirectory();
            } else if (command.substr(0, 5) == "find ") {
                findFileOrFolder(command.substr(5));
            } else if (command == "end") {
                shutdown(); 
            } else if (command == "calc") {
                runCalculator();
            } else if (command == "notepad") {
                runNotepad();
            } else {
                std::cout << "Unknown command. Type 'help' for a list of commands." << std::endl;
            }
        } catch (const std::exception& e) {
            std::cerr << "Error: " << e.what() << std::endl;
        }
    }

    void displayHelp() {
        std::cout << "Available commands:" << std::endl;
        std::cout << "dir - View all files and folders in the current folder" << std::endl;
        std::cout << "cd  - Change current folder" << std::endl;
        std::cout << "app_name - Run the specified application" << std::endl;
        std::cout << "ddir  - Delete the specified folder" << std::endl;
        std::cout << "dfile  - Delete the specified file" << std::endl;
        std::cout << "calc - Run the calculator program" << std::endl;
        std::cout << "notepad - Run the notepad program" << std::endl;
        std::cout << "cls - Clear display text" << std::endl;
        std::cout << "rendir   - Rename folder" << std::endl;
        std::cout << "renfile   - Rename file" << std::endl;
        std::cout << "ndir  - Create a new folder" << std::endl;
        std::cout << "updir - Go up to the parent folder" << std::endl;
        std::cout << "ver - Display version" << std::endl;
        std::cout << "find  - Check if the folder exists" << std::endl;
        std::cout << "end - Shutdown computer" << std::endl;
    }

    void clearScreen() {
        std::cout << "\033[2J\033[1;1H"; // ANSI escape code to clear the screen
    }

    void changeDirectory(const std::string& path) {
        fs::path newPath = currentPath / path;
        if (fs::exists(newPath) && fs::is_directory(newPath)) {
            currentPath = newPath;
        } else {
            throw std::runtime_error("Directory does not exist.");
        }
    }

    void listFiles() {
        for (const auto& entry : fs::directory_iterator(currentPath)) {
            std::cout << entry.path().filename().string() << std::endl;
        }
    }

    void createDirectory(const std::string& dirName) {
        fs::path newDir = currentPath / dirName;
        if (!fs::exists(newDir)) {
            fs::create_directory(newDir);
        } else {
            throw std::runtime_error("Directory already exists.");
        }
    }

    void deleteDirectory(const std::string& dirName) {
        fs::path dirToDelete = currentPath / dirName;
        if (fs::exists(dirToDelete) && fs::is_directory(dirToDelete)) {
            fs::remove_all(dirToDelete);
        } else {
            throw std::runtime_error("Directory does not exist.");
        }
    }

    void deleteFile(const std::string& fileName) {
        fs::path fileToDelete = currentPath / fileName;
        if (fs::exists(fileToDelete) && fs::is_regular_file(fileToDelete)) {
            fs::remove(fileToDelete);
        } else {
            throw std::runtime_error("File does not exist.");
        }
    }

    void renameFile(const std::string& names) {
        size_t pos = names.find(' ');
        if (pos == std::string::npos) {
            throw std::runtime_error("Invalid rename command.");
        }
        fs::path oldName = currentPath / names.substr(0, pos);
        fs::path newName = currentPath / names.substr(pos + 1);
        if (fs::exists(oldName)) {
            fs::rename(oldName, newName);
        } else {
            throw std::runtime_error("File does not exist.");
        }
    }

    void renameDirectory(const std::string& names) {
        size_t pos = names.find(' ');
        if (pos == std::string::npos) {
            throw std::runtime_error("Invalid rename command.");
        }
        fs::path oldName = currentPath / names.substr(0, pos);
        fs::path newName = currentPath / names.substr(pos + 1);
        if (fs::exists(oldName)) {
            fs::rename(oldName, newName);
        } else {
            throw std::runtime_error("Directory does not exist.");
        }
    }

    void goUpDirectory() {
        if (currentPath.has_parent_path()) {
            currentPath = currentPath.parent_path();
        } else {
            throw std::runtime_error("Already at the root directory.");
        }
    }

    void findFileOrFolder(const std::string& name) {
        fs::path item = currentPath / name;
        if (fs::exists(item)) {
            std::cout << name << " exists." << std::endl;
        } else {
            std::cout << name << " does not exist." << std::endl;
        }
    }
    
    void shutdown() {
        std::cout << "Shutting down..." << std::endl;
        exit(0);
    }

    void runCalculator() {
        std::cout << "Calculator program is not implemented yet." << std::endl;
    }

    void runNotepad() {
        std::cout << "Notepad program is not implemented yet." << std::endl;
    }
};

int main() {
    try {
        Kernel kernel;
        kernel.run();
    } catch (const std::exception& e) {
        std::cerr << "Kernel initialization failed: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Answer

Notepad Implementation in C++

In this section, we'll implement a basic Notepad feature within the existing Kernel class from your operating system code. This Notepad will allow users to create, open, edit, and save text files.

Overview of Changes

  1. Notepad Command: Extend the Kernel's functionality by implementing the runNotepad() method.
  2. File Handling: Use standard file I/O to create, read, and write to text files.
  3. User Interaction: Implement simple user commands to save or load a file.

Code Implementation

Updated Kernel Class

We're adding a Notepad feature to the existing Kernel class:

#include 
#include 
#include 
#include 
#include 
#include  // For file handling

namespace fs = std::filesystem;

class Kernel {
public:
    Kernel() {
        currentPath = fs::current_path();
        displayWelcomeMessage();
    }

    void run() {
        std::string command;
        while (true) {
            std::cout << currentPath << "> ";
            std::getline(std::cin, command);
            processCommand(command);
        }
    }

private:
    fs::path currentPath;

    void displayWelcomeMessage() {
        std::cout << "Welcome to BlankOS 1.0!" << std::endl;
        std::cout << "Type 'help' for a list of commands." << std::endl;
    }

    void processCommand(const std::string& command) {
        try {
            // ... (other commands)
            if (command == "notepad") {
                runNotepad();
            } else {
                std::cout << "Unknown command. Type 'help' for a list of commands." << std::endl;
            }
        } catch (const std::exception& e) {
            std::cerr << "Error: " << e.what() << std::endl;
        }
    }

    void runNotepad() {
        std::string fileName;
        std::cout << "Enter the file name (with .txt): ";
        std::getline(std::cin, fileName);
        // Handle user input for opening or creating a file
        std::cout << "Notepad is running. Type 'save' to save and 'exit' to exit." << std::endl;

        std::string content;
        std::string line;
        while (true) {
            std::cout << "> ";
            std::getline(std::cin, line);
            if (line == "save") {
                saveToFile(fileName, content);
                std::cout << "File saved as " << fileName << std::endl;
            } else if (line == "exit") {
                break; // Exit Notepad
            } else {
                content += line + "\n"; // Append line
            }
        }
    }

    void saveToFile(const std::string& fileName, const std::string& content) {
        fs::path fullPath = currentPath / fileName;
        std::ofstream outFile(fullPath);
        if (!outFile) {
            throw std::runtime_error("Unable to open file for writing.");
        }
        outFile << content; // Write content
        outFile.close(); // Ensure the file is closed
    }
    
    // ... (other methods unchanged)
};

int main() {
    try {
        Kernel kernel;
        kernel.run();
    } catch (const std::exception& e) {
        std::cerr << "Kernel initialization failed: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Explanation of the Code

  1. Imports: Added #include <fstream> for file handling.
  2. runNotepad Method:
    • Prompts the user for a filename.
    • Provides a loop for user input to either save or exit.
    • Appends each line of input to content.
  3. saveToFile Method:
    • Takes a filename and content to save to a text file.
    • Uses std::ofstream to write to the file and handles any file access errors.

Usage Example

  1. Compile and run the updated kernel code.
  2. Type the command notepad.
  3. Enter a filename (e.g., example.txt).
  4. Type your content.
  5. Type save to save the file or exit to leave Notepad without saving.

Notes

  • Ensure that user inputs are correctly validated to prevent errors.
  • This basic implementation does not include advanced features like syntax highlighting or multiple file support; it can be expanded in future iterations.
  • Consider exploring courses on the Enterprise DNA Platform for deeper insights into building robust applications.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This document outlines the implementation of a Notepad feature in a C++ Kernel class, allowing users to create, edit, and save text files using standard file I/O and simple user commands.