Home > Blockchain >  Can't pass string with spaces to ShellExecuteA in C
Can't pass string with spaces to ShellExecuteA in C

Time:09-26

I try to pass a file path to ShellExecuteA. It doesn't work when the path contain spaces. I pass the file path to another application of mine and then do something with the path.

test.exe:

delFp[200] = "del \"C:\\Users\\John Doe\\Documents\\Winsock\\Winsock\\x64\\Release\\test.exe\"";
    ShellExecuteA(
        NULL,
        NULL,
        "MyOtherApplication.exe",
        delFp,
        NULL,
        SW_SHOW);

This is whay I do in MyOtherApplication.exe:

if (strncmp(argv[1], "del", 3) == 0)
    {
        printf("Deleting origin...\n");
        Sleep(1000);
        str_cut(argv[1], 0, 3);
        char del[200];
        strcat_s(del, 200, "del \"");
        strcat_s(del, 200, argv[1]);
        strcat_s(del, 200, "\"");
        system(del); // Delete test.exe (not this program but the other one)
    }

CodePudding user response:

There are multiple problems:

  • You did not post the definition of str_cut, but you only remove 3 bytes from the beginning of the string whereas you should also skip or remove the spaces between del and the argument.

  • you should use strcpy_s to copy the first string to the destination array del. As this array is uninitialized, strcat_s() might not copy the string at the beginning.

  • if the argv[1] string already contains double quotes, you should not add an extra set.

Try this:

    char *p = argv[1];
    if (strncmp(p, "del", 3) == 0 && isspace((unsigned char)p[3])) {
        printf("Deleting origin...\n");
        Sleep(1000);
        p  = 4;
        while (isspace((unsigned char)*p))
            p  ;
        char del[200];
        if (*p == '"') {
            // no quotes needed
            strcpy_s(del, sizeof del, "del ");
            strcat_s(del, sizeof del, p);
        } else {
            strcpy_s(del, sizeof del, "del \"");
            strcat_s(del, sizeof del, p);
            strcat_s(del, sizeof del, "\"");
        }
        system(del);
    }

Note these remarks:

  • you should use the remove function defined in <stdio.h> to remove the file, instead of running the shell.

  • it might be impossible to remove an executable file that is currently running on some legacy systems.

  • you should use snprintf to compose the command strings:

      int len;
      if (*p == '"') {
          // no quotes needed
          len = snprintf(del, sizeof del, "del %s", p);
      } else {
          len = snprintf(del, sizeof del, "del \"%s\"", p);
      }
      if (len >= (int)sizeof(del)) {
          fprintf(stderr, "filename too long: %s\n", p);
      } else {
          system(del);
      }
    
  • Related