Created
December 17, 2020 14:28
-
-
Save amattu2/18ba149d1b9e24b0e1567d3701c9880c to your computer and use it in GitHub Desktop.
A simple ANSI-C I/O demonstration. Reads a username and password from stdin, performs tab/newline replacement on the username/password.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ANSI-C C90: -std=c99 -c -Wall -ansi -pedantic-errors -fstack-protector-all -Werror -Wshadow | |
Build: gcc username-pass-io.c -o io.o | |
*/ | |
/* | |
Produced 2020 | |
By https://amattu.com/links/github | |
Copy Alec M. | |
License GNU Affero General Public License v3.0 | |
*/ | |
/* | |
Description: | |
- Read a username and password from stdin | |
- Perform simple whitespace replacement | |
- Display username and password | |
*/ | |
/* Files */ | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
/* Input Config */ | |
#define MAX_USER_LEN 25 | |
#define MAX_PASS_LEN 45 | |
/* Function prototypes */ | |
static char* trim_whitespace(char *input); | |
/* Main Program */ | |
int main() { | |
/* Variables */ | |
char *username = NULL, | |
*password = NULL; | |
/* Allocate Variable Spacing */ | |
if (!(username = malloc(MAX_USER_LEN))) | |
return 1; | |
if (!(password = malloc(MAX_PASS_LEN))) | |
return 1; | |
/* Read Username */ | |
while (!username || strlen(username) <= 0 || strlen(username) > MAX_USER_LEN) { | |
printf("Please enter your username: "); | |
fgets(username, MAX_USER_LEN, stdin); | |
username = trim_whitespace(username); | |
} | |
/* Read Password */ | |
while (!password || strlen(password) <= 0 || strlen(password) > MAX_PASS_LEN) { | |
printf("Please enter your password: "); | |
fgets(password, MAX_PASS_LEN, stdin); | |
password = trim_whitespace(password); | |
} | |
/* Display results */ | |
printf("\n---------->[ Results ]<----------\n"); | |
printf("Username [%03d]: %s\nPassword [%03d]: %s\n", (int) strlen(username), | |
username, (int) strlen(password), password); | |
/* Default */ | |
return 0; | |
} | |
/* Remove tabs/newlines from char string | |
returns NULL on errors */ | |
static char* trim_whitespace(char *input) { | |
/* Variables */ | |
char *output; | |
int i = 0; | |
int nsi = 0; | |
if (!(output = malloc(strlen(input)))) | |
return NULL; | |
/* Loops */ | |
while (input[i]) { | |
if (input[i] != '\t' && input[i] != '\n') | |
output[nsi++] = input[i]; | |
i++; | |
} | |
/* Return */ | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment