Problem in sprintf function

I use code to crack rar passwords. I read the password from the file and pass it to the sprintf function. This is the code.

FILE* fp = fopen("password.txt","r"); while ( fgets ( pword, sizeof(pword), fp ) != NULL ) { sprintf(command, "rar e -p%s realp.rar", pword); printf(command); //system(command); } 

This code looks great, but it does not work. Therefore, I commented on the functioning of the system and printed out the variable "command". The output is as follows:

 rar e -pfirstpassword realp.rarrar e -psecondpassword realp.rarrar e -pthirdpassword realp.rarrar e -pfourthpassword realp.rar 

I see how it breaks. The result should look like this.

 rar e -pfirstpassword realp.rar rar e -psecondpassword realp.rar rar e -pthirdpassword realp.rar rar e -pfourthpassword realp.rar 

Can someone help me solve this? Thanks in advance.

  • operating system
  • : windows 7
  • compiler: dev C ++
+4
source share
2 answers

The new line found by fgets () is stored in 'pword'. Delete it, and then print each line with \ n and see if it works.

See the fgets () man page.

Try adding the following line after calling fgets ().

 pword[strlen(pword) - 1] = '\0'; 
+2
source

Every time your loop for a while loop is followed by a new line. Thus, the conclusion:

 rar e -pfirstpassword [NEWLINE] realp.rar 

You do not end the command with a new line. Thus, the conclusion:

 [command1][command2][command3] 

Combining the two problems (adding curly braces around each iteration of the loop, you get:

 {rar e -pfirstPassword [NEWLINE] realp.rar}{rar e -psecondPassword [NEWLINE] realp.rar} 

To fix the problem. Remove new lines from the end of each line of password.


To expand: The fgets documentation for windows is available here: http://msdn.microsoft.com/en-us/library/c37dh6kf(VS.80).aspx

From the documentation:

The fgets function reads a string from the input stream argument and stores it on the street. fgets reads characters from the current position of the stream and including the first character of a new line, until the end of the stream or until the number of characters read is n - 1, whichever comes first. The result stored in str is added using the null character. A new line character, if read, is included in the line.

Therefore, the Newline character is included as part of the line written for pword. Since you do not delete this character, a new line appears in the middle of the command when you write it with printf.

+1
source

All Articles