c++linux系统命令

c++ linux system command

本文关键字:系统命令 c++linux      更新时间:2023-10-16

我有以下问题:

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

  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());