[英]c++ linux system command
我有以下問題:
我在我的程序中使用這個 function:
system("echo -n 60 > /file.txt");
它工作正常。
但我不想擁有恆定的價值。 我這樣做:
curr_val=60;
char curr_val_str[4];
sprintf(curr_val_str,"%d",curr_val);
system("echo -n curr_val_str > /file.txt");
我檢查我的字符串:
printf("\n%s\n",curr_val_str);
是的,沒錯。 但是在這種情況下system
不起作用並且不返回-1。 我只是打印字符串!
如何傳輸像 integer 這樣的變量,這些變量將打印在像 integer 這樣的文件中,但不要字符串?
所以我想要變量 int a 並且我想在文件中使用系統 function 打印 a 的值。 我的 file.txt 的真實路徑是 /proc/acpi/video/NVID/LCD/brightness。 我不能用 fprintf 寫。 我不知道為什么。
你不能像你試圖做的那樣連接字符串。 嘗試這個:
curr_val=60;
char command[256];
snprintf(command, 256, "echo -n %d > /file.txt", curr_val);
system(command);
system
function 接受一個字符串。 在您的情況下,它使用文本 *curr_val_str* 而不是該變量的內容。 而不是使用sprintf
來生成數字,而是使用它來生成您需要的整個系統命令,即
sprintf(command, "echo -n %d > /file.txt", curr_val);
首先確保命令足夠大。
在您的情況下實際(錯誤地)執行的命令是:
"echo -n curr_val_str > /file.txt"
相反,您應該這樣做:
char full_command[256];
sprintf(full_command,"echo -n %d > /file.txt",curr_val);
system(full_command);
#define MAX_CALL_SIZE 256
char system_call[MAX_CALL_SIZE];
snprintf( system_call, MAX_CALL_SIZE, "echo -n %d > /file.txt", curr_val );
system( system_call );
正確的方法類似於:
curr_val=60;
char curr_val_str[256];
sprintf(curr_val_str,"echo -n %d> /file.txt",curr_val);
system(curr_val_str);
只是不要。 :)
為什么要使用system()
進行如此簡單的操作?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int write_n(int n, char * fname) {
char n_str[16];
sprintf(n_str, "%d", n);
int fd;
fd = open(fname, O_RDWR | O_CREAT);
if (-1 == fd)
return -1; //perror(), etc etc
write(fd, n_str, strlen(n_str)); // pls check return value and do err checking
close(fd);
}
您是否考慮過使用 C++ 的 iostreams 工具而不是使用echo
? 例如(未編譯):
std::ostream str("/file.txt");
str << curr_val << std::flush;
或者,您傳遞給system
的命令必須完全格式化。 像這樣的東西:
curr_val=60;
std::ostringstream curr_val_str;
curr_val_str << "echo -n " << curr_val << " /file.txt";
system(curr_val_str.str().c_str());
使用snprintf
來避免安全問題。
怎么樣使用std::string
& std::to_string
...
std::string cmd("echo -n " + std::to_string(curr_val) + " > /file.txt");
std::system(cmd.data());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.