Search code examples
cwindowsrustsystem

Can't call chcp from the system method


Hello I want to run the command chcp 65001 from my program via the windows api call system.

My program is written in rust but uses external c.

extern "C" {
    pub fn system(command: *const u8);
}

fn main() {
    unsafe {
        system("\"\"chcp\" \"65001\"\"".as_ptr());
    }
    // do work
}

The call works but I can't manage to format the string to pass into system properly.

I tried the following compbinations following to this question.

"\"\"chcp\" \"65001\"\"" (rust format)
With this result: Parameterformat wrong - "65001"

I also tried some other variants without success:
"\"\"chcp\" 65001\""
result: Parameterformat wrong - /rustc

"\"\"chcp 65001\""
result the system can't find the given path

The first variant seam fine the only problem is that chcp does complain about \"

Do you have an Idea how to pass it?

BONUS: Why does '/rustc' appear in variant 2.

Thank you for your help!


Solution

  • Rust strings are not NUL-terminated, so your call to system is reading whatever there is in memory after your string. I guess that's where your /rustc comes from. You need to convert your string to a CString to ensure that it is properly terminated:

    system (CString::new ("chcp 65001").unwrap().as_ptr());