Skip to content

Instantly share code, notes, and snippets.

@parzibyte

parzibyte/leer.c Secret

Created March 23, 2022 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/493de950c6183e0b51f3aded3feec851 to your computer and use it in GitHub Desktop.
Save parzibyte/493de950c6183e0b51f3aded3feec851 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define TECLA_BORRAR 8
#define TECLA_ENTER 13
#define MAXIMA_LONGITUD_CADENA 1000
#define MASCARA '*'
/*
https://parzibyte.me/blog
*/
void limpiarPantalla()
{
// system("cls"); // Comentar en Linux y descomentar en Windows
printf("\e[1;1H\e[2J"); // Comentar en Windows y descomentar en Linux
}
void enmascaraCadena(char *cadena, int longitud, char mascara)
{
int i = 0;
for (i = 0; i < longitud; i++)
{
printf("%c", mascara);
}
}
void leerContrasenaSinMostrarla(char *palabraSecretaDestino)
{
int caracterLeido = 0;
char temporal[2];
while (caracterLeido != TECLA_ENTER)
{
limpiarPantalla();
printf("Ingresa tu palabra secreta: ");
enmascaraCadena(palabraSecretaDestino, strlen(palabraSecretaDestino), MASCARA);
caracterLeido = getch();
// https://parzibyte.me/blog/2019/11/02/c-char-a-string/
temporal[0] = caracterLeido;
temporal[1] = '\0';
if (caracterLeido == TECLA_BORRAR)
{
if (strlen(palabraSecretaDestino) > 0)
{
// https://parzibyte.me/blog/2022/03/23/eliminar-ultimo-caracter-cadena-c/
palabraSecretaDestino[strlen(palabraSecretaDestino) - 1] = '\0';
}
}
else if (caracterLeido != TECLA_ENTER)
{
strncat(palabraSecretaDestino, temporal, 1);
}
}
}
int main()
{
char palabraSecreta[MAXIMA_LONGITUD_CADENA] = "";
leerContrasenaSinMostrarla(palabraSecreta);
// Nota: obviamente si no quieres mostrarla no la muestres, de todos modos la contraseña ya estará en palabraSecreta
printf("\nLo que escribiste es: '%s'", palabraSecreta);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment