clinuxgetchconio

What do I need to change to make this C programm work on Linux?


I need to make this work Linux, I know that conio.h is not for Linux and the main problem is getch() function. I tried using another lib like curses.h but still I got a lot of errors. It takes users input of password and converts it to **** for safety reasons.

Old code:

#include<stdio.h>
#include<conio.h>

void main()
{
    char password[25],ch;
    int i;

    clrscr();
    puts("Enter password: ");

    while(1)
    {
        if(i<0)
            i=0;
        ch=getch();

        if(ch==13)
            break;

        if(ch==8)
        {
            putch('b');
            putch(NULL);
            putch('b');
            i--;
            continue;
        }

        password[i++]=ch;
        ch='*';
        putch(ch);
    }

    password[i]='';
    printf("\nPassword enterd : %s",password);
    getch();
}

Updated code based on @SouravGhosh's answer:

#include<stdio.h>

int main(void)
{
    char password[25],ch;
    int i;

    //system("clear");
    puts("Enter password: ");

    while(1)
    {
        if(i<0)
            i=0;
        ch=getchar();

        if(ch==13)
            break;

        if(ch==8)
        {
            putchar('b');
            putchar('b');
            i--;
            continue;
        }

        password[i++]=ch;
        ch='*';
        putchar(ch);
    }

    password[i]=' ';
    printf("\nPassword enterd : %s",password);
    getchar();
    return 0;
}

Solution

  • If your terminal supports these escape codes, this will conceal typing as the password is entered.

    #include <stdio.h>
    
    void UserPW ( char *pw, size_t pwsize) {
        int i = 0;
        int ch = 0;
    
        printf ( "\033[8m");//conceal typing
        while ( 1) {
            ch = getchar();
            if ( ch == '\r' || ch == '\n' || ch == EOF) {//get characters until CR or NL
                break;
            }
            if ( i < pwsize - 1) {//do not save pw longer than space in pw
                pw[i] = ch;       //longer pw can be entered but excess is ignored
                pw[i + 1] = '\0';
            }
            i++;
        }
        printf ( "\033[28m");//reveal typing
        printf ( "\033[1;1H\033[2J");//clear screen
    }
    
    int main ( ) {
        char password[20];
    
        printf ( "Enter your password: ");
        fflush ( stdout);//prompt does not have '\n' so make sure it prints
        UserPW ( password, sizeof ( password));//password array and size
        printf ( "\nentered [%s]\n", password);//instead of printing you would verify the entered password
        return 0;
    }