Search code examples
cwindowswinapicommand-promptwindows-console

Write input to console using C


Let's say I am changing the password of a user,

#include <stdio.h>
#include <stdlib.h>

int main() {
  system("net user myUsername *");
  return 0;
}

and when run this program, I get back

Type a password for the user:

How do I write to the console with a function without manually typing on to the keyboard? Is there some function like

writeConsoleWindow("myPass");
submitConsole();

Solution

  • Use CreateProcess() to launch cmd.exe (which is what system() does) with a redirected STDIN handle, then you can write data to cmd in your code. See Creating a Child Process with Redirected Input and Output.

    However, in the specific case of net user commands, you should be using functions like NetUserGetInfo(), NetUserSetInfo(), NetUserChangePassword(), etc instead.