c++linux系统命令
c++ linux system command
我有以下问题:
我在我的程序中使用这个函数:
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%sn",curr_val_str);
是的,这是对的。但是CCD_ 1在这种情况下不起作用并且不返回-1。我只是打印字符串!
我如何传输像integer这样的变量,这些变量将像integer一样打印在文件中,但不传输字符串?
所以我想要一个变量int a,我想要在文件中打印一个带有系统函数的值。我的文件.txt的真实路径是/proc/acpi/video/NVID/LCD/亮度。我不会用fprintf写字。我不知道为什么。
您无法像尝试那样连接字符串。请尝试以下操作:
curr_val=60;
char command[256];
snprintf(command, 256, "echo -n %d > /file.txt", curr_val);
system(command);
system
函数采用一个字符串。在您的案例中,它使用的是文本*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 );
man snprintf
正确的方法类似于此:
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());
相关文章:
- 提供变量作为 MATLAB 系统命令的输入参数,以便C++可执行文件
- 将系统命令打印到文本文件 C++
- 使用系统命令时发送输入不起作用
- 有没有一种简单的方法可以将系统命令的输出转换为字符串
- C++中的程序如何使用"系统"变量与 Linux 中的 shell 脚本交互?
- 如何将 c ++ 变量的值传递给 hadoop HDFS 的 bash 系统命令?
- 来自C 应用程序的运行系统命令与Commandline不同
- CPP中的管道内部(AWK)系统命令
- C++:如何运行一个系统命令N次(异步)并返回N次执行时间
- 使用 C++ 更改注册表值?(系统命令失败)
- Qt::如何识别/检测系统是否被Linux中的其他系统远程访问
- 使用系统命令调用可执行文件
- c++系统命令
- 如何在C++中通过将每个命令分配给线程来同时执行linux系统命令
- C++函数系统(命令)的输出在Linux终端中不显示颜色
- Execlp()不接受参数列表,只接受命令.UNIX/LINUX编程
- 使用Windows技术检测复制,粘贴,打印系统命令
- 使用系统命令从 Windows 下的 C 程序内部更改目录
- Linux c++系统命令失败
- c++linux系统命令