尝试做一个简单的c++ shell



我想在c++中做一个简单的shell,但我有一些麻烦,使它工作:

#pragma warning (disable : 4996)
#include <iostream>
#include <string>
#include <chrono>
#include <ctime>
#include <filesystem>
#include <fstream>
#ifdef _WIN64
#include <direct.h>
#else
#include <unistd.h>
#endif
#define clear cout << "33[H33[J"
#define MAXLETTER 1000
#define MAXCOMMAND 1000
using namespace std;
const string currentDateTime() {
time_t     now = time(0);
struct tm  tstruct;
char       buf[128];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%d/%m/%Y, %X", &tstruct);
return buf;
}
void help() {
cout << "core's shell, build 0 from September, 2021." << endl;
cout << "Available commands:" << endl;
cout << "exit - exit shell" << endl;
cout << "cd - changes current working directory" << endl;
cout << "help - shows this message" << endl;
cout << "chprompt - changes shell's prompt" << endl;
}
void start() {
string username = getenv("USERNAME");
cout << "Welcome to core's shell, " << username << "." << endl;
cout << currentDateTime() << endl;
}
int main() {
string prompt = ": ";
string command;
const char* command_list[8];
command_list[0] = "exit";
command_list[1] = "cd";
command_list[2] = "help";
command_list[3] = "chprompt";
command_list[4] = "start";
int switch_arg = 0;
const char* dir = getenv("CD");
string history("history.csh");
fstream history_file;
clear;
start();
command:
history_file.open(history, ios::out);
cout << prompt;
getline(cin, command);
if (history_file.is_open()) {
history_file << command;
}
switch (switch_arg) {
case 1:
history_file.close();
exit(0);
case 2:
_chdir(dir);
return 0;
break;
case 3:
help();
return 0;
break;
case 4:
cout << "Type in your prompt: ";
cin >> prompt;
break;
case 5:
start();
break;
default:
cout << "Command not found" << endl;
goto command;
}
return 0;
}

我如何在字符串上使用case使我的命令工作?

是否有更好的方法来创建命令历史?

我是根据下面的代码来编写这段代码的:https://www.geeksforgeeks.org/making-linux-shell-c/

如果这个问题很愚蠢,我很抱歉,我对c++很生疏。

嗯,就我所知,没有办法在字符串上使用switch-case语句。我相信你可以在这里找到答案——为什么switch语句不能应用于字符串?

还可以使用map,将字符串值映射为整数值。它看起来像这样-

std::map<std::string, int> cmds = {
{"cd", 1},
{"ls", 2}
};
switch (map[cmd]){
...
}

其中CMD为输入命令,CMDS包含所有命令。

相关内容

  • 没有找到相关文章

最新更新