c++ linux system command
I have the following problem:
I use in my program this function:
system("echo -n 60 > /file.txt");
it works 开发者_如何转开发fine.
But I don't want to have constant value. I do so:
curr_val=60;
char curr_val_str[4];
sprintf(curr_val_str,"%d",curr_val);
system("echo -n curr_val_str > /file.txt");
I check my string:
printf("\n%s\n",curr_val_str);
Yes,it is right.
but system
in this case doesn't work and doesn't return -1. I just print string!
How can I transfer variable like integer that will be printed in file like integer, but don't string?
So I want to have variable int a and I want to print value of a with system function in file. A real path to my file.txt is /proc/acpi/video/NVID/LCD/brightness. I can't write with fprintf. I don't know why.
you cannot concatenate strings like you are trying to do. Try this:
curr_val=60;
char command[256];
snprintf(command, 256, "echo -n %d > /file.txt", curr_val);
system(command);
The system
function takes a string. In your case it's using the text *curr_val_str* rather than the contents of that variable. Rather than using sprintf
to just generate the number, use it to generate the entire system command that you require, i.e.
sprintf(command, "echo -n %d > /file.txt", curr_val);
first ensuring that command is large enough.
The command that is actually (erroneously) executed in your case is:
"echo -n curr_val_str > /file.txt"
Instead, you should do:
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
The correct way would be similar to this:
curr_val=60;
char curr_val_str[256];
sprintf(curr_val_str,"echo -n %d> /file.txt",curr_val);
system(curr_val_str);
Just DON'T. :)
Why resort to system()
for such a simple operation?
#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);
}
Have you considered using C++'s iostreams facility instead of shelling out to echo
? For example (not compiled):
std::ostream str("/file.txt");
str << curr_val << std::flush;
Alternately, the command you pass to system
must be fully formatted. Something like this:
curr_val=60;
std::ostringstream curr_val_str;
curr_val_str << "echo -n " << curr_val << " /file.txt";
system(curr_val_str.str().c_str());
Use snprintf
to avoid security issues.
What about using std::string
& std::to_string
...
std::string cmd("echo -n " + std::to_string(curr_val) + " > /file.txt");
std::system(cmd.data());
精彩评论