1

I'm writing a few functions for getting and storing a user password. It's all working OK but is there any way of replacing what is typed at the prompt with an asterisk, for example?

This is fairly standard behaviour in windowed applications I've had a good look through the C libraries but all of the fgets/getc type functions don't seem to offer any control over this.

EDIT: trying to do this with ANSI C, running on OS X. Answers below have pointed me in the right direction - my search didn't turn up a few of the links...

cortexlock
  • 1,446
  • 2
  • 13
  • 26
  • 3
    DUplicate: http://stackoverflow.com/questions/6856635/hide-password-input-on-terminal – Rafael Baptista May 08 '13 at 18:53
  • This depends on what you are writing exactly and how you are writing it. If you are just capturing the users input and then printing it back out then you can handle that by replacing characters. – Connor Hollis May 08 '13 at 18:53
  • Check if your libc knows the `getpass` function. – ott-- May 08 '13 at 18:53
  • @Connor should have been clearer in my question - wanted to turn the echo off. Just wasn't using the right terminology - I managed to replace what the user typed with asterisks once they've hit ENTER by copying/modifying the string, but the screen echo remained. – cortexlock May 08 '13 at 19:06

3 Answers3

4

Assuming POSIX:

struct termios t;
tcgetattr(STDIN_FILENO, &t);
t.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);

Then no user input will be echoed. Set back the ECHO flag if you want to undo this.

3

Sure, use some kind of terminal control library to disable character echo and then print whatever you like. Possibilities:

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Thanks Carl. I'm teaching myself C the hard way at the moment - would this be possible without using an external library (i.e. C plus the "usual suspect" libraries like stdlib, stdio and string? If this would be a massive effort then it's probably way beyond my level, but interested nonetheless – cortexlock May 08 '13 at 18:54
  • @GasMan14 1. "usual suspect" is called the C standard library, 2. See my answer - on POSIX systems (which you *should* use when learning C) the termios API is standard and can be relied upon. –  May 08 '13 at 18:55
1

You didn't say which platform or compiler, but see ANSI C No-echo keyboard input. Maybe getch() or kbhit() or getpass(), depending on environment.

Community
  • 1
  • 1
jarmod
  • 71,565
  • 16
  • 115
  • 122