0

The idea

scanning a password entered by the user and showing ********** in place of P@$$w00r_D

explaining the code

inside a while loop keep scanning the characters using getch() and put them into an array password[], until the user press return

The Code

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

#define TRUE 1 
#define P_MAX 25

int main(int argc, char* argv[]) {
   char password[P_MAX], ch;
   int i = 0;

   puts("Enter the password [MAX 25]: ");
   while (TRUE) {
      if (i < 0) {
         i = 0;
      }//end if
      ch = getch();

      if (ch == 13)//return
         break;
      if (ch == 8) // BACKSPACE
      {
         putch('b');
         putch(NULL);//Overwrite that character by NULL.
         putch('b');
         i--;//Decrement Current Track of Character. (i)
         continue;
      }//end if
          password[i++] = ch;
          ch = '*';
      putch(ch);
   }//end while

   printf("\nPassword Entered : %s", password);//test
   getch();
return 0;
}//end main

Compiling on Unix machine

[ar.lnx@host Documents] $ gcc 115.c -o x
115.c:2:18: fatal error: conio.h: No such file or directory
compilation terminated.
[ar.lnx@host Documents] $

this code works fine on windows, but not in Unix. any help?

0x0584
  • 258
  • 1
  • 7
  • 15
  • 1) Use standard C boolean type and constants. Do not use homebrew stuff like `TRUE`. 2) Use only standard C features. 3) In Linux/Unix use PAM. – too honest for this site Feb 17 '16 at 22:19
  • 4
    `conio.h` is a windows-only library. You'll need to get rid of it and use something in a portable standard. – Gillespie Feb 17 '16 at 22:19
  • 1
    @RPGillespie It's actually and old MS-DOS header. It's not a library! – Iharob Al Asimi Feb 17 '16 at 22:20
  • @iharob I use the word "library" very loosely - It could mean header file, package, object archive, shared object, etc. – Gillespie Feb 17 '16 at 22:22
  • can't we just use `if, #elif, #else, and #endif ` Directives to switch between the libraries? @RPGillespie ? – 0x0584 Feb 17 '16 at 22:26
  • Yes, you can use preprocessor directives for windows or linux-only code – Gillespie Feb 17 '16 at 22:29
  • 1
    Don't take the "portable" word too seriously. At some point your program interacts with the OS and needs to rely on OS-specific features (the console/terminal in your case). You may use conditional compilation, rely on a lib that does it for you or go with the standards (lowest common denominator). –  Feb 17 '16 at 22:31
  • 1
    Also, have you read this thread yet? http://stackoverflow.com/questions/6856635/hide-password-input-on-terminal – Gillespie Feb 17 '16 at 22:32
  • Thanks for this, this helps a lot – 0x0584 Feb 17 '16 at 22:35
  • On UNIX-like systems, you could either directly call termios (the terminal driver) to turn off echoing or you could use a high-level library like curses or getline. Getline is actually portable and compiles on Windows, too. – fuz Feb 17 '16 at 23:08

0 Answers0