How to use the double quote in Command without "\"

Hey guys, I juest starting to learn rust.
I want to modify the file in "program files", the fs module is not work, so I'm trying to use Command.
here is my code

use std::process::Command;

fn main() {
  let cmd = Command::new("cmd")
    .arg("/C")
    .arg(r#"echo move ^"A^" ^"B^""#)
    // .arg("&&pause")
    .spawn()
    .expect("run failed");
  match cmd.wait_with_output() {
    Ok(_) => {
      println!("end");
    }
    Err(err) => {
      println!("error: {}", err.to_string());
    }
  }
}

the output should be

>cmd /c "echo move ^"A^" ^"B^""
move "A" "B"

but now, it is

move \"A^\" \"B^\"

how to fix it?
or is there a better way to modify the file in the "Program Files"?

If it doesn't work because of a permission issue, then no amount of escaping strings in Rust is going to help. You haven't specified why it didn't work, and I wouldn't expect the fs module to have any problems manipulating files in Program Files (assuming you have the right permissions).

Anyway, this looks like it does what you want:

use std::os::windows::process::CommandExt;
use std::process::Command;

fn main() {
  let cmd = Command::new("cmd")
    .arg("/C")
    .raw_arg(r#"echo move ^"A^" ^"B^""#)
    .spawn()
    .expect("run failed");
  match cmd.wait_with_output() {
    Ok(_) => {
      println!("end");
    }
    Err(err) => {
      println!("error: {}", err.to_string());
    }
  }
}

Note the use of raw_arg to prevent the standard library from escaping the contents of the argument.

1 Like

cmd's quotation and scaping rules are notoriously complicated.

what do you mean by "should be"? you are spawning a process directly, not running it from an interactive shell, there should not be any "echo back" behavior.

also, I believe cmd doesn't use backslash as escape character. how did you get that output string? are you formatting it in any way?

just to clarify, by "echo back", I mean the "cmd /c blablablah" line, not the echo command.

thanks! it's worked.
I just wrote a demo to modify a file using fs, but it worked, I don't know why it didn't work before, but I can confirm that I ran it as administrator.
I'll keep looking for problems.

Thanks for your reply.
I apologize for my unclear description.
The issue with escaped characters has been solved.

hey, I have found the problem.
I've tried before to use the handle I get from File::open to write to the file, but it's read-only, so it doesn't work.
thanks again. :relieved: