-3

I am using Ubuntu20.04. When programming with C/C++ to create CLI applications, I'd like to be able to input something private such as password. In particular, I need my input not showing on the screen when I type the password.


Update:

Not sure why this is closed for not having enough focus. I think I have been as specific as possible:

  • Platform: ubuntu 20.04
  • Language: C/C++
  • What I am doing: to create a CLI application that allows me to input passwords.
  • What I want: the input not showing on my screen while I am typing it.
pynexj
  • 19,215
  • 5
  • 38
  • 56
ihdv
  • 1,927
  • 2
  • 13
  • 29
  • Why the downvote? If it's because I was asking for the C++ solution and the Python solution at the same time, I've already edited the question. – ihdv Nov 24 '20 at 01:55
  • @tdelaney: The man page for [`getpass()`](https://man7.org/linux/man-pages/man3/getpass.3.html) says `This function is obsolete. Do not use it.` – Bill Lynch Nov 24 '20 at 02:05
  • https://stackoverflow.com/questions/1196418/getting-a-password-in-c-without-using-getpass-3 might be useful, although it uses c i/o instead of c++. – Bill Lynch Nov 24 '20 at 02:08
  • @BillLynch Thanks. I'll take a look. c i/o is also okay for me. – ihdv Nov 24 '20 at 02:16
  • Not sure why the downvotes, but the question's title did strike me as strange. It might be better to gear the title towards the more general case, along the lines of "Getting user input without it displayed in the console". Your question is already somewhat oriented on the general case, but it's also a bit short. Perhaps you are simply being concise, but you might want to give the question a once-over with a mindset centered on the general case. – JaMiT Nov 24 '20 at 02:16
  • @JaMiT I dare not make it more general than this...it is already closed for "needs more focus". – ihdv Nov 24 '20 at 02:30

1 Answers1

0

You can use terminal I/O api to do this.

#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int main()
{
    struct termios old_tio, new_tio;
    unsigned char c;

    /* get the terminal settings for stdin */
    tcgetattr(STDIN_FILENO,&old_tio);

    /* we want to keep the old setting to restore them a the end */
    new_tio=old_tio;

    /* disable canonical mode (buffered i/o) and local echo */
    new_tio.c_lflag &=(~ICANON & ~ECHO);

    /* set the new settings immediately */
    tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);

    int i = 0;
    char password[100] = {0}; // hardcode with max 100 char input
    do {
         c=getchar();
         password[i++] = c;
         printf("*");
    } while(c!='\n' || i == 100);

    printf("%s\n", password);

    /* restore the former settings */
    tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);

    return 0;
}
binhgreat
  • 982
  • 8
  • 13