views:

94

answers:

3

I mean i want the input to be invisible like inputing password when i log in Linux. How can I implement it both in C under linux and windows. thanx

A: 

To my understanding, there is no standard input routine for inputting without echo. You'll have to use platform specific functions.

However, if you are using a GUI framework, some have text input fields for passwords and are compatible on Windows and Linux.

Thomas Matthews
+3  A: 

There is no single solution that will work across platforms.

For Linux you can use the getpass() function.

For windows you can try _getch().

codaddict
hi, in windows _getch() seems it only get one char at one time....Can i get a string by anyfunctions?
Macroideal
I'm not aware of any function that does not echo and return a string. You can call _getch() in a loop, appending the char entered to a string and break when a newline is encountered.
codaddict
+2  A: 

stty(1) works for me in Linux

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

int main(void) {
  char buf1[100], buf2[100];
  size_t len1, len2;

  system("stty -echo");
  printf("Enter Password: ");
  fflush(stdout);
  fgets(buf1, sizeof buf1, stdin);
  len1 = strlen(buf1);
  if (len1 && buf1[len1 - 1] == '\n') buf1[--len1] = 0;
  puts("");

  system("stty echo");
  printf("Enter Password again: ");
  fflush(stdout);
  fgets(buf2, sizeof buf2, stdin);
  len2 = strlen(buf2);
  if (len2 && buf2[len2 - 1] == '\n') buf2[--len2] = 0;

  puts("\n\n");
  printf("First password: [%s]\n", buf1);
  printf("Second password: [%s]\n", buf2);
  return 0;
}
pmg