c ++ linux系统命令

Teb*_*ebe 7 c c++ linux system function

我有以下问题:

我在我的程序中使用这个函数:

  system("echo -n 60  > /file.txt"); 
Run Code Online (Sandbox Code Playgroud)

它工作正常.

但我不想拥有恒定的价值.我这样做:

   curr_val=60;
   char curr_val_str[4];
   sprintf(curr_val_str,"%d",curr_val);
   system("echo -n  curr_val_str > /file.txt");
Run Code Online (Sandbox Code Playgroud)

我检查我的字符串:

   printf("\n%s\n",curr_val_str);
Run Code Online (Sandbox Code Playgroud)

是的,这是对的.但system在这种情况下不起作用,并且不返回-1.我只是打印字符串!

如何传输变量,如整数,将在整数文件中打印,但不串?

所以我想要变量int a,我想在文件中打印一个带有系统函数的值.我的file.txt的真实路径是/ proc/acpi/video/NVID/LCD/brightness.我不能用fprintf写.我不知道为什么.

Con*_*ius 9

你不能像你想要的那样连接字符串.试试这个:

curr_val=60;
char command[256];
snprintf(command, 256, "echo -n %d > /file.txt", curr_val);
system(command);
Run Code Online (Sandbox Code Playgroud)

  • 这对于使用`snprintf`而不是`sprintf`来说值得+1. (3认同)

bor*_*ble 8

system函数采用字符串.在你的情况下,它使用文本*curr_val_str*而不是该变量的内容.而不是sprintf仅使用生成数字,使用它来生成您需要的整个系统命令,即

sprintf(command, "echo -n %d > /file.txt", curr_val);
Run Code Online (Sandbox Code Playgroud)

首先确保命令足够大.


Igo*_*Oks 7

在您的情况下实际(错误地)执行的命令是:

 "echo -n curr_val_str  > /file.txt"
Run Code Online (Sandbox Code Playgroud)

相反,你应该这样做:

char full_command[256];
sprintf(full_command,"echo -n  %d  > /file.txt",curr_val);
system(full_command);
Run Code Online (Sandbox Code Playgroud)