简体   繁体   中英

windows system command redirection in c

I can get the redirection to work from the command line but I cannot get the redirection to work from my C code. Any suggestions are greatly appreciated!

// This works: -hashfile command completed successfully.

memset(&tchar[0], 0, sizeof(tchar));
sprintf(tchar, "certutil -hashfile \"\%s\"\ MD5", output_file);  
system(tchar);

This doesn't --> Error: Expected no more than 2 args, received 4

sprintf(tchar, "certutil -hashfile \"\%s\"\ MD5 ^> "\C:\\TEMP\\image.cksm\"\"", output_file); 

There are problems with sprintf 's format argument which is invalid:

  • Compile error : the dblquote( " ) from " \\C:\\... is ending the format string, making the rest of it (path) illegal.
  • Runtime error : the caret( ^ ) from ^ > makes the following redirecting operator ( > ) to be treated as a literal (as a consequence as a program argument; same thing with the following filename), so certutil receives 4 arguments instead of (the expected) 2. You only need to escape special chars if you want to treat them as literals, and discard their special meaning.
  • Some over ( C ) escaping: the 2nd and 4th backslashes( \\ ) from \\" \\ %s\\" \\ - not critical, but over-complicates the string.

To make it work, change the code to:

sprintf(tchar, "certutil -hashfile \"%s\" MD5 > \"C:\\TEMP\\image.cksm\"", output_file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM