Trong công việc để tool hóa các công việc, chúng ta nghĩ đến bài toán tạo một app bởi chính C++ để thực hiện một công việc nào đó liên quan đến dòng lệnh
Về cơ bản, chúng ta cần 2 thứ:
- Get thông tin từ dòng lệnh (output của một câu lệnh nào đó)
- Dựa trên thông tin get được ở No.1, ta thực hiện điều ta muốn bởi một command khác.
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
int main()
{
cout << exec("cd /home/tuantitien/Desktop ; ls -la");
return 0;
}
console sẽ thu được kết quả:
total 20
drwxrwxrwx 4 tuantitien tuantitien 4096 Jan 18 05:08 .
drwxrwxrwx 21 tuantitien tuantitien 4096 May 16 10:44 ..
-rwxrwxrwx 1 tuantitien tuantitien 1159 Jun 29 2021 git_config.txt
drwxrwxrwx 5 tuantitien tuantitien 4096 Feb 11 05:25 KEM
drwxrwxrwx 3 tuantitien tuantitien 4096 Jan 18 04:47 setupAnhLT
Giả sử, căn cứ trên kết quả trả về, ta có thể làm một điều gì đó, giả sử xóa một file ta biết được trong list trả về của command "ls -la"
cout << exec("cd /home/gen5p/Desktop ; rm -r git_config.txt");
TuanTitien++