I am using this code to extract a password protected RAR file. I am using the std::system()
function to invoke the RAR command. If I use the password
in the std::system()
function, it works. But as tries to pass the password as parameter, it doesn't. For example, if in this code if I use password pwd
, it gives this error:
"pwd is not recognised as internal or external command, operable program or batch file."
But if I change the code and make it to system("rar e -ppwd wingen.rar")
, it works.
Can anybody explain what mistake I am making? Thanks in advance!
Here's my code:
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
char pword[20];
printf("enter the pword : ");
gets(pword);
system(("rar e -p%s wingen.rar",pword));
getchar();
return 0;
}
The system() function is a part of the C/C++ standard library. It is used to pass the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed. <stdlib. h> or <cstdlib> should be included to call this function.
The system function passes command to the command interpreter, which executes the string as an operating-system command. system uses the COMSPEC and PATH environment variables to locate the command-interpreter file CMD.exe. If command is NULL , the function just checks whether the command interpreter exists.
If you're just doing some quick testing on one platform, using system() is perfectly fine, but you shouldn't use it in production environments, unless you really have to. For example, you could allow the user to set an external program that is then executed. For something like this system() is perfectly fine.
system()
only takes one argument - a const char*
. In fact,
system( "rar e -p%s wingen.rar", pword );
won't compile - the compiler will complain that you've passed too many arguments to system()
. The reason that:
system( "rar e -p%s wingen.rar", pword );
compiles is that you have wrapped your two strings in parenthesis. This has the effect of evaluating the expression inside, which consists of the comma operator operating on two strings. The comma operator has the effect of returning the value of the second argument, so you end up calling:
system( pword );
Which in your example is equivalent to:
system( "pwd" );
And pwd
isn't a command on your system (although on POSIX systems it is... but I digress). What you want to do has been explained in the other answers but for completeness I'll mention it too - you need to format your string using sprintf
:
char buff[256];
sprintf( buff, "rar e -p%s wingen.rar", pword );
or you can concatenate strings, which might be a little bit faster (although for such a short string, it probably won't make a difference):
char buff[256] = "rar e -p";
strcat( buff, pword );
strcat( buff, " wingen.rar" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With