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 @   十一的杂文录  阅读(696)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示