C++执行Linux命令

 

 

一、执行简单命令

比如需要创建文件、文件夹、删除文件

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    // 执行简单的 shell 命令
    std::string cmd = "mkdir heihei";
    int res = system(cmd.c_str());
    if(res == 0)
    {
        std::cout << "创建成功" << std::endl;
    }
    else
    {
        std::cout << "创建失败" << std::endl;
    }
    return 0;
}

 

 

 

二、执行稍复杂命令

比如cat,查看文件,获取文件内容

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    // 执行 cat 命令,获取文件内容
    std::string cmd = "cat /sys/class/video4linux/video0/device/modalias";
    
    FILE *fp;
    fp = popen(cmd.c_str(), "r");
    char buf[100];
    fgets(buf, sizeof(buf), fp);
    fclose(fp);

    std::cout << buf << std::endl;
    
    return 0;
}

 

 

posted @ 2023-10-31 15:24  十一的杂文录  阅读(406)  评论(0编辑  收藏  举报