2011-06-28 178 views
7

我有以下問題:C++ linux系統命令

我在程序中使用此功能:

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。我只是打印字符串!

我該如何傳輸整數等變量,這些整數將以整數形式打印在文件中,但不要串入?

所以我想有變量int a,我想打印文件中的系統函數的值。我的file.txt的真正路徑是/ proc/acpi/video/NVID/LCD /亮度。我不能用fprintf寫。我不知道爲什麼。

+0

你會發現很多問題試圖寫多語言的源文件是什麼。我建議你堅持只使用C或C++中的一種。 – pmg

回答

9

你不能連接字符串,就像你正在做的那樣。試試這個:

curr_val=60; 
char command[256]; 
snprintf(command, 256, "echo -n %d > /file.txt", curr_val); 
system(command); 
+2

對於使用'snprintf'而不是'sprintf'來說,這值得使用+1。 –

4
#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); 

​​

8

system函數採用一個串。在你的情況下,它使用文本* curr_val_str *而不是該變量的內容。而不是使用sprintf剛剛產生的數量,用它來生成你需要對整個系統的命令,即

sprintf(command, "echo -n %d > /file.txt", curr_val); 

首先確保命令是足夠大的。你的情況

7

,實際上是命令(錯誤地)執行的是:

"echo -n curr_val_str > /file.txt" 

相反,你應該做的:

char full_command[256]; 
sprintf(full_command,"echo -n %d > /file.txt",curr_val); 
system(full_command); 
2

正確的方法與此類似:

curr_val=60; 
char curr_val_str[256]; 
sprintf(curr_val_str,"echo -n %d> /file.txt",curr_val); 
system(curr_val_str); 
2

只是不。 :)

爲什麼要使用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); 

} 
2

你有沒有考慮過使用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()); 
0

有關使用std::string & std::to_string ...

std::string cmd("echo -n " + std::to_string(curr_val) + " > /file.txt"); 
std::system(cmd.data());