Inserting Into Text File Blank - c

I ask for two simple user inputs, a user and a password, I then insert those into a text file, each followed by a semi colon. The semi colons save and the password saves but the username doesn't save for some odd reason.
For example if I input Joe with password 111222444555 it'll
display as ;111222444555; instead of Joe;111222444555;
Code:
int main()
{
int Number_Of_Attempts = 3;
int result = 0;
char userID[32];
printf("Please enter your user id\n");
scanf("%s", &userID);
char password[12];
printf("The user has not been found. Please enter your a password\n");
scanf("%s", &password);
printf("Username and Password has been saved");
printf("\n");
InsertIntoHash(userID, password);
return 0;
}
void InsertIntoHash(char *userID, char *hash)
{
FILE *fp;
fp = fopen("HashTable.txt", "a");
fprintf(fp, userID);
fprintf(fp,";");
fprintf(fp, hash);
fprintf(fp, ";\n");
fclose(fp);
}

You should read in the string using scanf("%31s", userID); for the userID and scanf("%11s", password); for the password.
What I think causes the problem is, that you declare and define InsertIntoHashafter the main function, without declaring a prototype at the beginning.
So the code should be the following: (I tested it and it works)
#include <stdio.h>
#include <stdlib.h>
void InsertIntoHash(char *userID, char *hash);
int main() {
int Number_Of_Attempts = 3;
int result = 0;
char userID[32];
printf("Please enter your user id\n");
scanf("%31s", userID);
char password[12];
printf("The user has not been found. Please enter your a password\n");
scanf("%11s", password);
printf("Username and Password has been saved");
printf("\n");
InsertIntoHash(userID, password);
return 0;
}
void InsertIntoHash(char *userID, char *hash) {
FILE *fp;
fp = fopen("HashTable.txt", "a");
fprintf(fp, userID);
fprintf(fp,";");
fprintf(fp, hash);
fprintf(fp, ";\n");
fclose(fp);
}
I hope I could help you! :)

Change scanf("%s", &userID); to scanf("%s", userID); as it is already an array which will be passed as a pointer. Same for password.
Note the buffer for password is too small: the password is 12 chars and the buffer too so the terminating null character is placed outside the buffer (resulting in Undefined Behavior, as you encounter).
Use "%11s" to limit the length read to the size of the buffer, leaving room for the terminating null character.

Related

How to get integer and string input using scanf?

I have a problem in C language
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char usrname[17] = "nsa-secret-agent";
char password[9] = "marshal41";
char usr[512], pass[512];
printf("username: ");
scanf("%[^\n]%*c", usr);
printf("password: ");
scanf("%[^\n]%*c", pass);
printf("%s\n", usr);
printf("%s\n", pass);
if (strcmp(usrname, usr) == 0 && strcmp(password, pass) == 0){
printf("You Have Successfully Logged In!\n");
}
else{
printf("username or password not found!\n");
exit(0);
}
return 0;
}
When I run this code it runs without any errors but when give input like below:
username: nsa-secret-agent
password: marshal41
nsa-secret-agent
marshal41
username or password not found!
I am giving correct credentials but still it's showing error
Your arrays for usrname and password are off by one:
char usrname[17] = "nsa-secret-agent";
char password[9] = "marshal41";
These are short one byte for the zero terminator which makes the comparison later fail. Either add one or just use
char usrname[] = "nsa-secret-agent";
char password[] = "marshal41";
or you could even use
char *usrname = "nsa-secret-agent";
char *password = "marshal41";
since the strings are not modified.

Encryption in C using a Caesar Cipher

I have been asked to create a program where I have to encrypt multiple pieces of information using a Caesar Cipher. I understand the concept behind it but what I'm having trouble visually is how to enter pieces of data within the function. For example, I have encrypted passwords saved in a file ("hrkk1" meaning "pass1" and so on). I have to create a cipher function to read the input from a scanf and strcmp so it matches what's in the file allowing the user to login.
Whats the best way to validate the user input and make "pass1" turn into "hrkk1" so it matches what's in the file and allows user login?
Thank you
This is the code I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <windows.h>
void checkValid(void);
void loginDetails(char username[5][6], char password[5][9]);
void encryption(char username[5][6], char password[5][9]);
int main(void)
{
FILE *EP;
FILE *UN;
char username[5][6];
char password [5][9], ch, key;
EP = fopen("encrypted_passwords.txt", "r");
fscanf(EP, "%s %s %s %s %s", password[0], password[1],
password[2], password[3], password[4]);
fclose(EP);
UN = fopen("username.txt", "r");
fscanf(UN, "%s %s %s %s %s", username[0], username[1], username[2],
username[3], username[4]);
fclose(UN);
printf("Welcome.");
loginDetails(username, password);
return 0;
}
void loginDetails(char username[5][6], char password[5][9])
{
int i;
char nurseUsername[6];
char nursePassword[6];
bool useValid = 0;
bool passValid = 0;
printf("Please Enter your username: \n");
scanf("%s", nurseUsername);
for (i = 0; i < 5; i++)
{
if(strcmp(nurseUsername, username[i]) == 0)
{
useValid = 1;
}
}
if(useValid != 1)
{
printf("\nError. Invalid Username. Returning to menu.\n");
Sleep(1000);
system("cls");
main();
}
else
{
printf("\nPlease enter your password: \n");
scanf("%s", nursePassword);
}
for(i = 0; i < 5; i++)
{
if((strcmp(nurseUsername, username[i]) == 0) &&
(strcmp(nursePassword, password[i]) == 0))
{
passValid = 1;
}
if(passValid != 1)
{
printf ("Error. Invalid Password. Returning to menu.\n");
Sleep(1000);
system("cls");
main();
}
else
{
printf("\nLogin Successful. Loading menu.\n");
Sleep(1000);
system("cls");
patientEntry();
}
}
}
You need to use the shifting of the character in c. This is possibile with a simple addition( or subtraction) on a char value.
Pay attention your example doesn't shift the number character and maybe also the character doesn't go out the alphabet, and it take in consideration also the capital letters. So pay attention when you do the addition to not exceed the range of capital or non capital letter. My suggestion is to use ascii table.

Save text to file permanently and read from it

Hello everyone i have to do simple login program in C, i have a problem to save username, full name and password because i need to choose '1' for sign up and '2' for sign in but always when i exit the console and try to read my file everything disappears.
#include <stdio.h>
int main() {
FILE *f = fopen("users.txt", "w+");
if (f == NULL) {
printf("N/A");
exit(1);
}
int choose,
username[15],
fullName[20],
password[15],
// confirmPassword[15];
printf("Welcome!\n");
printf(" 1: Sign up\n 2: Sign in\n");
printf("--------------------------------\n");
scanf("%d", &choose);
if(choose==1) {
printf("Username: ");
scanf("%s", &username);
printf("Full name: ");
scanf("%s", &fullName); /// BECAUSE OF SPACE IT COUNTS LIKE A PASSWORD
printf("Password: ");
scanf("%s", &password);
fprintf(f, "%s\n%s\n%s", username, fullName, password);
}
if(choose==2) {
char c;
printf("Username: ");
while( c != EOF) {
c = fgetc(f);
printf("%c",c);
}
}
fclose(f);
return 0;
}
I have to deal with HASH too but i will try that on my own. And help about /// comment !
As per previous comments, and with my idea, here is how you may fix the code:
1. use int c or unsigned int c to declare c variable.
2. set c tp be (whatever as long it is not EOF);
3. make do while loop that at the end checks for EOF.

fgets - crashes in visual studio, works in gcc

I'm working on something small and I have run into a really small but disturbing problem - the program works in gcc, but crashes in visual studio, when it gets to the fgets command:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void registerUser(char *username);
char path[256] = "C:\\Users\\magshimim\\Desktop\\cproject\\bank\\";
int main() {
int choice = 0;
char username[10];
printf("Welcome to nikitosik's bank program!\n"
"Choose an option :\n"
"0 - Register\n"
"1 - Login to existing account\n");
scanf("%d", &choice);
getchar(); // catch enter
if (!choice) {
registerUser(username);
} else {
//login();
}
}
void registerUser(char *username) { // username is passed, for verification later
FILE *userinfo; // file that contains info of all registered users
FILE *userpathf; // file to open for txt file
char usertxt[256]; // path of data
char userpath[256]; // path of new user data file
char password[15];
strcat(userpath, path);
strcat(usertxt, path);
strcat(usertxt, "users.txt");
userinfo = fopen(usertxt, "a");
printf("Choose a username(max 10 letters): ");
fgets(username, 10, stdin);
username[strcspn(username, "\n")] = 0;
strcat(userpath, username);
strcat(userpath, ".txt");
userpathf = fopen(userpath, "w");
fclose(userpathf);
printf("Choose a password(max 15 letters): ");
fgets(password, 15, stdin);
fprintf(userinfo, "%s\n%s", username, password);
fclose(userinfo);
}
thanks in advance
As above really or initialize the strings first.
memset(userpath, 0, sizeof(userpath));
memset(usertxt, 0, sizeof(usertxt));
Your program has multiple issues:
you concatenate a string into an uninitialized array: this has undefined behavior and may well explain the observed behavior on different systems as undefined behavior may take multiple forms from no consequence at all to a crash or possibly even worse misfortune.
you do not test the return values of scanf, fopen, fgets(). Any invalid or unexpected input may trigger more undefined behavior.
you do not check for potential buffer overflow in strcat(). You should instead use snprintf().
Here is a safer version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int registerUser(char *username, size_t size);
char path[] = "C:\\Users\\magshimim\\Desktop\\cproject\\bank\\";
int main(void) {
int choice = 0;
int c;
char username[10];
printf("Welcome to nikitosik's bank program!\n"
"Choose an option :\n"
"0 - Register\n"
"1 - Login to existing account\n");
if (scanf("%d", &choice) != 1)
return 1;
// consume the rest if the input line
while ((c = getchar()) != EOF && c != '\n')
continue;
if (choice == 0) {
registerUser(username, sizeof(username));
} else {
//login();
}
return 0;
}
int registerUser(char *username, size_t size) { // username is passed, for verification later
char usertxt[256]; // path of data
char userpath[256]; // path of new user data file
char password[17];
FILE *userinfo; // file that contains info of all registered users
FILE *userpathf; // file to open for txt file
printf("Choose a username(max %d letters): ", (int)(size - 2));
if (!fgets(username, size, stdin))
return -1;
username[strcspn(username, "\n")] = 0; // strip newline if any
printf("Choose a password(max 15 letters): ");
if (!fgets(password, sizeof(password), stdin))
return -1;
password[strcspn(password, "\n")] = 0; // strip newline if any
if (snprintf(usertxt, sizeof(usertxt), "%s%s", path, "users.txt") >= (int)sizeof(usertxt))
return -1;
if (snprintf(userpath, sizeof(userpath), "%s%s.txt", path, username) >= (int)sizeof(userpath))
return -1;
userinfo = fopen(usertxt, "a");
if (userinfo == NULL)
return -1;
// create user file
userpathf = fopen(userpath, "w");
if (userpathf != NULL)
fclose(userpathf);
// add user info
fprintf(userinfo, "%s\n%s\n", username, password);
fclose(userinfo);
return 0;
}

scanf not responding?

Ive recently begun learning C and am trying to write a password data protection program. Im writing a function which should test to see if a file, password.txt exists if it doesnt it will get a null value and then ask the user to set a master password and to repeat. However it doesnt allow the user to repeat the password. Any tips? - Cheers (Keep in mind just C not C++)
/*Headers*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_LENGTH 99
int main(void){
/*Variable Declaration*/
char password[] = "Lakaka";
masterPassword();
printf("Welcome to Fort-Knox.");
getchar();
return 0;
}
int masterPassword(void){
/*Password Comparison Variables*/
char password[MAX_LENGTH];
char password1[MAX_LENGTH];
FILE*fp;
if (fp == NULL){
printf("Choose a master password:\n");
scanf("%c", password);
printf("Please repeat password:\n");
scanf("%c", password1);
if (password == password1){
printf("Password Accepted.");
fp = fopen("password.txt", "w+");
printf("File Created");
fclose(fp);
return 0;
}
}
}
Use %s not %c as format specifier, when reading a string. %c only reads a single character.
Your formatting specifier is wrong.
This is also wrong:
if (password == password1)
this will only compare the arrays converted to pointers. You need to compare character-by-character, by calling strcmp():
if( strcmp(password, password1) == 0 )
{
printf("match!\n");
}
use "%s" instead of "%c"
%c is for only 1 character
%s is for string
scanf("%s", password);
scanf("%s", password1);
you need to do
scanf("%s", password);
and to compare use :
strncmp(password,password1,MAX_LENGTH)
it´s always more safe :)...

Resources