亲宝软件园·资讯

展开

C++模拟Linux Shell编写一个自定义命令

DEFAULT 人气:0

本文将根据C++模拟Linux Shell写一个自定义命令,下面是示例代码,需要的可以参考一下

示例代码

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "stdarg.h"
using namespace std;

#define MAXLEN 200

void write2File(const std::string &file_string, const std::string str_content);
void readFromFile(string file_string);
string getParamStr(char *ch_pt);
void ProcessByPattern(char *ptr, ...);

/*如果不存在file,则会在当前文件夹下创建file*/
void write2File(const std::string &file_string, const std::string str_content)
{
    if (file_string.empty())
    {
        cout << "empty file string name!" << endl;
        return;
    }
    else if (str_content.empty())
    {
        cout << "empty content string!" << endl;
        return;
    }

    std::ofstream OsWrite(file_string, std::ofstream::app);
    OsWrite << str_content;
    OsWrite << std::endl;
    OsWrite.close();
}

void readFromFile(string file_string)
{
    if (file_string.empty())
    {
        cout << "empty file string name!" << endl;
        return;
    }

    string line;

    std::ifstream labels(file_string.c_str());
    if (!labels.is_open())
    {
        cout << "maybe the file is not exist, can not open the file! " << endl;
        return;
    }

    while (std::getline(labels, line))
    {
        cout << line << endl;
    }
}

string getParamStr(char *ch_pt)
{
    string str;
    char *ptr = new char[MAXLEN];

    ptr = ch_pt;
    str = ptr;

    cout << "parameter: " << str << endl;
    return str;
}

/* ... : 不定参数 */
void ProcessByPattern(char *ptr, ...)
{
    string pattern_str = getParamStr(ptr);
    va_list ap;
    va_start(ap, ptr);

    if (pattern_str == "-r")
    {
        // va_arg(ap, type): 获取下一个type类型的参数
        char *para_ptr = va_arg(ap, char *);
        string readFileStr = getParamStr(para_ptr);
        readFromFile(readFileStr);
    }
    else if (pattern_str == "-w")
    {
        char *file_ptr = va_arg(ap, char *);
        char *cont_ptr = va_arg(ap, char *);

        string filename = getParamStr(file_ptr);
        string cont_str = getParamStr(cont_ptr);
        write2File(filename, cont_str);
    }
    else
    {
        cout << "pattern is empty or pattern number is wrong" << endl;
    }

    va_end(ap);
}

int main(int argc, char *argv[])
{
    // cout<<argc<<endl;
    // cout<<argv[0]<<endl;
    // cout<<argv[1]<<endl;
    if (argc < 2)
    {
        cout << "no arguments pass throught command line" << endl;
        return -1;
    }

    cout << "请输入模式和参数:" << endl;
    cout << "如: -r filename, 即从filename逐行读取内容并打印" << endl;
    cout << "-w filename content, 向filename写入content" << endl;
    cout << "若写入的文件对象不存在,则其将会被创建" << endl;

    ProcessByPattern(argv[1], argv[2], argv[3]);

    return 0;
}

g++ mine_shell_0.1.cpp -o mine_shell_0.1

./mine_shell_0.1 -w y.log 99999999999999999999999999

./mine_shell_0.1 -r y.log  
99999999999999999999999999

想让它更像shell命令的话,三种方式:

加载全部内容

相关教程
猜你喜欢
用户评论