在 Linux 下用 C++ 写脚本并实现自动化,通常有几种常见思路和做法,取决于你说的“脚本”是指:
下面我按常见场景给你一个清晰总结。
C++ 本身不是脚本语言,但完全可以像脚本一样用。
#include <cstdlib>
#include <iostream>
int main() {
system("ls -l");
system("cp a.txt b.txt");
system("echo done");
return 0;
}
编译并运行:
g++ auto.cpp -o auto
./auto
✅ 适合:文件处理、批量任务、调用命令
system()(最简单)system("mkdir -p build && cd build && cmake ..");
⚠️ 缺点:不安全、难捕获输出
popen()(可获取输出)#include <cstdio>
#include <iostream>
int main() {
FILE* pipe = popen("ls", "r");
char buf[128];
while (fgets(buf, sizeof(buf), pipe)) {
std::cout << buf;
}
pclose(pipe);
}
<filesystem> + POSIX(更专业)#include <filesystem>
namespace fs = std::filesystem;
fs::copy("a.txt", "b.txt", fs::copy_options::overwrite_existing);
cron 定时执行crontab -e
示例(每分钟执行):
* * * * * /home/user/auto/auto >> log.txt
创建服务:
# /etc/systemd/system/auto.service
[Unit]
Description=Auto Task
[Service]
ExecStart=/home/user/auto/auto
systemctl start auto
all:
g++ main.cpp -o main
make
cmake -B build
cmake --build build
✅ 推荐模式
#!/bin/bash
g++ task.cpp -o task
./task
加可执行权限:
chmod +x run.sh
./run.sh
可以用:
<std::process>(未来)boost.processsubprocess(C++17)示例(boost):
boost::process::system("ls");
| 需求 | 推荐方式 |
|---|---|
| 简单自动化 | C++ + system |
| 定时任务 | cron / systemd |
| 复杂流程 | Shell 调 C++ |
| 服务器长期运行 | systemd |
| 工程化 | CMake + CI |
如果你能说清楚:
我可以直接给你一套可抄的模板。