programs/C2.c
changeset 28 10da75d5db5d
equal deleted inserted replaced
27:5bf1f248407c 28:10da75d5db5d
       
     1 #include <stdio.h>
       
     2 #include <stdlib.h>
       
     3 #include <string.h>
       
     4 
       
     5 // for installation notes see C0.c
       
     6 // this program can be called with
       
     7 //
       
     8 //  ./args2-good | ./C2
       
     9 //
       
    10 // or
       
    11 //
       
    12 // ./args2-bad | ./C2
       
    13 
       
    14 
       
    15 int match(char *s1, char *s2) {
       
    16   while( *s1 != '\0' && *s2 != 0 && *s1 == *s2 ){
       
    17     s1++; s2++;
       
    18   }
       
    19   return( *s1 - *s2 );
       
    20 }
       
    21 
       
    22 // since gets() is insecure and produces lots of warnings, 
       
    23 // I use my own input function instead ;o)
       
    24 char ch;
       
    25 int i;
       
    26 
       
    27 void get_line(char *dst) {
       
    28   char buffer[8];
       
    29   i = 0;
       
    30   while ((ch = getchar()) != '\n') {
       
    31     buffer[i++] = ch; 
       
    32   }
       
    33   buffer[i] = '\0';
       
    34   strcpy(dst, buffer);
       
    35 }
       
    36 
       
    37 void welcome() { printf("Welcome to the Machine!\n"); exit(0); }
       
    38 void goodbye() { printf("Invalid identity, exiting!\n"); exit(1); }
       
    39 
       
    40 main(){
       
    41   char name[8];
       
    42   char pw[8]; 
       
    43 
       
    44   printf("login: "); 
       
    45   get_line(name);
       
    46   printf("password: "); 
       
    47   get_line(pw);
       
    48 
       
    49   if(match(name, pw) == 0)
       
    50     welcome();
       
    51   else
       
    52     goodbye();
       
    53 }
       
    54