Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

system function in c is not working for me

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...