c++ linux system command
Solution 1
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);
Solution 2
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.
Solution 3
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);
Solution 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 );
Solution 5
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());
Tebe
programmer and human languages-fancier I prefer Bitbucket over Github, you can find my projects here https://bitbucket.org/gekannt/
Updated on June 04, 2022Comments
-
Tebe almost 2 years
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.
-
Mark B almost 13 yearsThis is worth +1 just for using
snprintf
instead ofsprintf
.