C++ Linux系统命令

7
我是一个有用的助手,可以为您翻译文本。
我遇到了以下问题:
在我的程序中,我使用了以下函数:
  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,并且我想使用system函数将a的值打印到文件中。我的文件.txt的实际路径是/proc/acpi/video/NVID/LCD/brightness。我无法使用fprintf进行写入。我不知道为什么。


你在编写多语言源文件时会遇到许多问题。我建议你只使用C或C++中的一种。 - pmg
9个回答

9

您不能像您尝试的那样连接字符串。请尝试以下操作:

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

3
仅仅因为使用了snprintf而不是sprintf,这就值得+1分。 - Mark B

8
< p > 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);

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

man snprintf


3

你是否考虑过使用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());

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

正确的方式类似于这样:

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

1

使用snprintf来避免安全问题。


0

使用 std::stringstd::to_string 怎么样?

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接