details about the questions ..........................................................................
/*here is my edited code . You may try create a random credential on
dat file . I have edited the code and add on structure , however my
login part seems not initializing my input from the dat file. */.
the login part unable to validate if username is already exist in the dat file . the code will just skipped to "Kindly key in correct password " even if the username is exist in the dat file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
struct login1{
char username[20];
char password[15];
char name[20];
char address[30];
char pnum[12];
};
void login(void)
{
FILE*fptr;
fptr = fopen("customertest.dat","r");
char username[20];
char password[15];
int try=0;
struct login1 l;
if(fptr == NULL)
{
printf("Error! The file does not exist.");
exit(0);
}
system("CLS");
printf("\nInsert username : ");
scanf("%s", username);
printf("\nInsert password : ");
scanf("%s", password);
//while(fread(&l, sizeof(l), 1, fptr))
if((fscanf(fptr,"%s %s ", username, password))!=EOF)
{
if(strcmp(username, l.username)==0 && strcmp(password,
l.password)==0)
{
printf("\nLogin sucess");
printf("\nWelcome %s \n", l.username);
exit(0);
}
else if (strcmp(username, l.username) == 0 && strcmp(password,
l.password) == 1)
{
printf("Kindly key in correct password ");
exit(0);
}
else
{
printf("Kindly key in correct username and password");
exit(0);
}
}
fclose(fptr);
}
void registration(void) {
FILE*fptr;
fptr = fopen("customertest.dat","a+");
struct login1 l;
if(fptr == NULL)
{
printf("Error! The file does not exist.");
exit(0);
}
system("CLS");
printf("\nPlease enter the username : ");
scanf("%s",l.username);
fprintf(fptr, "%s\t" , l.username);
printf("\nPlease enter the password : ");
scanf("%s",l.password);
fprintf(fptr, "%s\t" , l.password);
printf("\nPlease enter your name : ");
scanf("%s",l.name);
fprintf(fptr, "%s\t" , l.name);
printf("\nPlease enter your address : ");
scanf(" %[^\n]s", l.address); // The [] is the scanset character.
[^\n] tells that while the input is not a newline ('\n') take input.
fprintf(fptr, "%s\t" , l.address);
printf("\nPlease enter your phone number : ");
scanf("%s",l.pnum);
fprintf(fptr, "%s\t" , l.pnum);
fprintf(fptr, "\n\n*********************************************
\n\n");
//fprintf(fptr, "%s\t%s\t%s\t%s\t%s\t" l.username, l.password,
l.name, l.address, l.pnum );
//fwrite(&l, sizeof(l), 1,fptr);
fclose(fptr);
printf("\nThank you. Your information is now saved to our database
!\n");
printf("You may now login to the website using to your username >>
%s <<\n\n\n", l.username);
printf("Registration process will exit now ! ");
}
int main() {
int opt;
printf("Kindly choose your action ? \n");
printf("Please key in as 1 for login and 2 for registration :\t");
scanf("%d" , &opt);
switch (opt)
{
case 1:
if (opt == 1)
printf("Welcome to Login page\n");
login();
case 2:
if (opt == 2)
printf("\nWelcome to Registration page ! \n");
registration();
default:
printf("\n\n\nKey in correct number either 1 or 2 . Program will exit
now ! ! ! \n\n\n");
}
}
Related
I'm new to C and trying to write a program for a hotel and let customers edit their booking details such as first name, last name...etc. The code I wrote can be run but the data in the file is not edited.
The else statement for the line ("Record not found! Please enter your Username and Password again.\n"); is not printed when I entered the wrong username and password as well.
Here is what I got so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct customer_details // Structure declaration
{
char uname[100];
char pass[100];
char fname[100];
char lname[100];
char ic[100];
char contact[100];
char email[100];
char room[100];
char day[100];
}s;
void main()
{
FILE* f, *f1;
f = fopen("update.txt", "r");
f1 = fopen("temp.txt", "w");
char uname[100], pass[100];
int valid = 0;
// validate whether file can be opened.
if (f == NULL)
{
printf("Error opening file!\n");
exit(0);
}
printf("Please enter your Username and Password to update your booking detail.\n");
printf("\nUsername: ");
fgets(uname, 100, stdin);
uname[strcspn(uname, "\n")] = 0;
printf("Password: ");
fgets(pass, 100, stdin);
pass[strcspn(pass, "\n")] = 0;
while (fscanf(f, "%s %s", s.uname, s.pass) != -1)
{
if (strcmp(uname, s.uname) == 0 && strcmp(pass, s.pass) == 0)
{
valid = 1;
fflush(stdin);
printf("Record found!\n");
printf("\nEnter First Name: ");
scanf("%s", &s.fname);
printf("\nEnter Last Name: ");
scanf("%s", &s.lname);
printf("\nEnter IC Number: ");
scanf("%s", &s.ic);
printf("\nEnter Contact Number:");
scanf("%s", &s.contact);
printf("\nEnter Email: ");
scanf("%s", &s.email);
printf("\nEnter Room ID :");
scanf("%s", &s.room);
printf("\nEnter Days of staying:");
scanf("%s", &s.day);
fseek(f, sizeof(s), SEEK_CUR); //to go to desired position infile
fwrite(&s, sizeof(s), 1, f1);
}
else
("Record not found! Please enter your Username and Password again.\n");
}
fclose(f);
fclose(f1);
if (valid == 1)
{
f = fopen("update.txt", "r");
f1 = fopen("temp.txt", "w");
while (fread(&s, sizeof(s), 1, f1))
{
fwrite(&s, sizeof(s), 1, f);
}
fclose(f);
fclose(f1);
printf("Record successfully updated!\n");
}
}
This is what the update.txt file contains:
abc 123 First Last 234 33667 hi#gmail.com 101 3
You forgot the printf call, change
("Record not found! Please enter your Username and Password again.\n");
to
printf("Record not found! Please enter your Username and Password again.\n");
If you compile your program with warnings enabled you should get a warning like
t.c:68:12: warning: statement with no effect [-Wunused-value]
("Record not found! Please enter your Username and Password again.\n");
^
I create a program that prompts the user to choose an option, like below:
create a file and name the file.
add component in the file
display the item in the file
exit program
So my problem is the file is created and exists in my directory, but it is empty, so where did I miss something? plus can you check whether the 2 and 3 option program are OK?
Here my program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num, name;
start:
printf("\n1. Create a file.");
printf("\n2. Add a component to the list.");
printf("\n3. Display the current list of component.");
printf("\n4. Exit program.");
printf("\n\nChoose either these four menu = ");
scanf("%d", &num);
fflush(stdin);
switch (num) {
case 1:
printf("\n\nPlease enter file name: ");
scanf("%d", &name);
FILE *pf = NULL;
char username[250];
char userfile[255];
printf("username: ");
scanf("%s", username);
sprintf(userfile, "%s.txt", username);
fflush(stdin);
goto start;
break;
case 2:
pf = fopen(userfile, "w");
if (!pf) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
struct date {
int day;
int month;
int year;
};
struct details {
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
struct details item[50];
int n, i;
printf("Enter number of items:");
scanf("%d", &n);
fflush(stdin);
for (i = 0; i < n; i++) {
fflush(stdin);
printf("Item name: \n");
scanf("%s", item[i].name);
fflush(stdin);
printf("Item code: \n");
scanf("%d", &item[i].code);
fflush(stdin);
printf("Quantity: \n");
scanf("%d", &item[i].qty);
fflush(stdin);
printf("price: \n");
scanf("%d", &item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy): \n");
scanf("%d-%d-%d", &item[i].mfg.day,
&item[i].mfg.month, &item[i].mfg.year);
}
fclose(pf);
goto start;
break;
case 3:
pf = fopen(userfile, "r");
if (!userfile) {
fprintf(stderr, "File opening failed!\n");
return EXIT_FAILURE;
}
{
printf(" ***** INVENTORY ***** \n");
printf("------------------------------------------------------------------\n");
printf("S.N.| NAME | CODE | QUANTITY | PRICE | MFG.DATE \n");
printf("-------------------------------------------------------- ---------\n");
for (i = 0; i < n; i++)
fprintf("%d %-15s %-d %-5d %-5d %d/%d/%d \n",
i + 1, item[i].name, item[i].code, item[i].qty,
item[i].price, item[i].mfg.day, item[i].mfg.month,
item[i].mfg.year);
printf("------------------------------------------------------------------\n");
}
fclose(pf);
goto start;
break;
case 4:
printf("Exit Program, Thank You, Sayonara");
break;
}
return 0;
}
There are multiple problems in your code:
the test if (!userfile) is incorrect: you should test if (!pf) instead
you open the file for reading, you should open it for writing with "w", or possibly for appending with "a".
you never write to the file. You should use fprintf(pf, ...) instead of printf.
the arrays userfile, item and variables i and n are local inside the switch statement: their contents go out of scope when you go to the start label outside de switch statement. Move all these definitions outside the switch statement.
fflush(stdin); has undefined behavior. You can consume (flush) the rest of the input line with: int c; while ((c = getchar()) != EOF && c != '\n') continue; You can define a function flush() that does it.
I created 2 function. One for login and another for signup. It's working fine for only one user but for multiple user it's not working. It's only read the first two string from the file. How can I fix it and make it to read second or more set of data from file?
Here is my code:
//login (reading data)
login() {
system("cls");
system("color 3");
char username[10], password[10], un[10], pwd[10];
FILE *fp;
fp = fopen("stored_data.txt","r");
fscanf(fp, "%s%s", username, password);
printf("Enter your username: ");
fflush(stdin);
gets(un);
printf("Enter your password: ");
fflush(stdin);
gets(pwd);
if ((strcmp(username,un)==0)&&(strcmp(password,pwd)==0)) {
printf("Login successful, welcome %s.\n",un);
}
else {
system("cls");
system("color 4");
printf("Invalid username or password.");
}
fclose(fp);
}
//Sign up (store data)
signup() {
system("cls");
system("color 3");
char username[10], un[10], pwd[10];
FILE *fp;
fp = fopen("stored_data.txt","r");
fscanf(fp, "%s", username);
fp = fopen("stored_data.txt","a");
printf("Enter your username: ");
fflush(stdin);
gets(un);
if((strcmp(username,un)==0)) {
printf("User already existed.\n");
}
else {
printf("Enter your password: ");
fflush(stdin);
gets(pwd);
fprintf(fp,"%s %s",un,pwd);
printf("New user's information added successfully.\n");
}
fclose(fp);
}
You should look for the name after the user entered his name and password.
By this line
fscanf(fp, "%s%s", username, password);
You are reading the first username and password in your file. Instead, you should move this into a while loop.
...
printf("Enter your username: ");
fflush(stdin);
gets(un);
printf("Enter your password: ");
fflush(stdin);
gets(pwd);
while(!feof(fp)){
fscanf(fp, "%s%s", username, password);
if (strcmp(username,un) == 0){
if(strcmp(password, pwd) == 0)
printf("Login successful, welcome %s.\n",un);
else break;
}
}
...
After some help if possible.
I have a class project that requires building a simple login and registration system, which also needs input validation for the password and username meeting length/character requirements.
I am an absolute beginner and really struggling. I haven't even got around to making the validation as the code I have so far can't compile. I understand it might look messy, but I do struggle with c programming.
Here is the error
login2.c: In function ‘login’:
login2.c:11:15: error: storage size of ‘l’ isn’t known
11 | struct login l;
Any help would be absolutely amazing.
Thanks in advance!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
login()
{
char username[30],password[20];
FILE *log;
log=fopen("login.txt","r");
struct login l;
printf("\nPlease Enter your login credentials below\n\n");
printf("Username: ");
fgets(username, 30, stdin);
printf("\nPassword: ");
printf("\n");
fgets(password, 20, stdin);
while(fread(&l,sizeof(l),1,log))
{
if(strcmp(username,l.username)==0 && strcmp(password,l.password)==0)
{
printf("\nSuccessful Login\n");
}
else
{
printf("\nIncorrect Login Details\nPlease enter the correct credentials\n");
}
}
fclose(log);
}
struct login
{
char fname[30];
char lname[30];
char username[30];
char password[20];
}
registration()
{
char firstname[15];
FILE *log;
log=fopen("login.txt","w");
struct login l;
printf("\nWelcome to your online course provider. We need to enter some details for registration.\n\n");
printf("\nEnter First Name:\n");
scanf("%c",l.fname);
printf("\nEnter Surname:\n");
scanf("%c",l.lname);
printf("Thank you.\nNow please choose a username and password as credentials for system login.\nEnsure the username is no more than 30 characters long.\nEnsure your password is at least 8 characters long and contains lowercase, uppercase, numerical and special character values.\n");
printf("\nEnter Username:\n");
scanf("%c",l.username);
printf("\nEnter Password:\n");
scanf("%c",l.password);
fwrite(&l,sizeof(l),1,log);
fclose(log);
printf("\nConfirming details...\n...\nWelcome, %c!\n\n",firstname);
printf("\nRegistration Successful!\n");
printf("Press any key to continue...");
getchar();
system("CLS");
login();
}
int main()
{
int option;
printf("Press '1' to Register\nPress '2' to Login\n\n");
scanf("%d",&option);
if(option == 1)
{
system("CLS");
registration();
}
else if(option == 2)
{
system("CLS");
login();
}
}
The compiler reads the file from top to bottom. This means the compiler don´t "know" what struct login is at the definition of l. The definition of the structure login needs either to be set before the definition of l or you need to do a forward declaration of the structure login.
Next thing is that the definition of login misses a ; at the end of it.
Also the definition head of login() shall be void login (void) and registration() shall be void registration (void).
Furthermore you use %c instead of %s when printing or input a string:
printf("\nEnter First Name:\n");
scanf("%c",l.fname);
or
printf("\nConfirming details...\n...\nWelcome, %c!\n\n",firstname);
Also ever check if the opening of a file was successful by checking the pointer returned for a null pointer:
log = fopen("login.txt","r");
if (log == NULL)
{
fputs("Error at opening File!", stderr);
exit(1);
}
As a side note you´re working code will probably skip:
fgets(username, 30, stdin);
in login() because you have the scanf() statement of:
scanf("%d",&option);
in the control flow before which leaves a newline character in stdin. This newline character is fetched by the fgets() call. Place a getchar() after scanf().
Corrected code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct login // before the first use of `l`.
{
char fname[30];
char lname[30];
char username[30];
char password[20];
};
void login (void);
void registration (void);
int main (void)
{
int option;
printf("Press '1' to Register\nPress '2' to Login\n\n");
scanf("%d",&option);
getchar(); // catching newline.
if(option == 1)
{
system("CLS");
registration();
}
else if(option == 2)
{
system("CLS");
login();
}
}
void login (void)
{
char username[30],password[20];
FILE *log;
log = fopen("login.txt","r");
if (log == NULL)
{
fputs("Error at opening File!", stderr);
exit(1);
}
struct login l;
printf("\nPlease Enter your login credentials below\n\n");
printf("Username: ");
fgets(username, 30, stdin);
printf("\nPassword: ");
printf("\n");
fgets(password, 20, stdin);
while(fread(&l,sizeof(l),1,log))
{
if(strcmp(username,l.username)==0 && strcmp(password,l.password)==0)
{
printf("\nSuccessful Login\n");
}
else
{
printf("\nIncorrect Login Details\nPlease enter the correct credentials\n");
}
}
fclose(log);
return;
}
void registration(void)
{
char firstname[15];
FILE *log;
log=fopen("login.txt","w");
if (log == NULL)
{
fputs("Error at opening File!", stderr);
exit(1);
}
struct login l;
printf("\nWelcome to your online course provider. We need to enter some details for registration.\n\n");
printf("\nEnter First Name:\n");
scanf("%c",l.fname);
printf("\nEnter Surname:\n");
scanf("%s",l.lname);
printf("Thank you.\nNow please choose a username and password as credentials for system login.\nEnsure the username is no more than 30 characters long.\nEnsure your password is at least 8 characters long and contains lowercase, uppercase, numerical and special character values.\n");
printf("\nEnter Username:\n");
scanf("%s",l.username);
printf("\nEnter Password:\n");
scanf("%s",l.password);
fwrite(&l,sizeof(l),1,log);
fclose(log);
printf("\nConfirming details...\n...\nWelcome, %s!\n\n",firstname);
printf("\nRegistration Successful!\n");
printf("Press any key to continue...");
getchar();
system("CLS");
login();
}
I already asked before and have done something that would work i think (but i'm a beginner so that story falls into a water) i have an error when i tried to sign up can anyone help? I have few more hours to send it (homework) AND i don't ask someone to do it for me, just to gimme instructions
#include <stdio.h>
#include <string.h>
int signIn(char username[30], char pass[30]){
FILE *p;
char user2[30], pass2[30];
p = fopen("users.txt", "r+");
fscanf(p,"%s\n%s",user2,pass2);
if( (strcmp(username,user2)==0) && (strcmp(pass,pass2)==0) )
printf("\nUser and password correct!!!");
else
printf("\nUser or password incorrect!\n\n");
printf("\n\n");
fclose(p);
return 0;
}
int signUp(char username[30], char pass[30], char fullName[30]) {
FILE *p;
p = fopen("users.txt", "r+");
printf("Username: ");
scanf("%s", &username);
printf("Password: ");
scanf("%s", &pass);
printf("Full name: ");
scanf("%s", &fullName);
fprintf(p, "%s\n%s\n%s", username, fullName, pass);
fclose(p);
return 0;
}
int main(){
char username[30], pass[30], fullName[30];
int choose;
printf("Welcome to student login system!\n");
printf(" 1: Sign in\n 2: Sign up\n");
printf("--------------------------------\n");
scanf("%d", &choose);
if(choose==1) {
printf("\nUser:");
scanf("%s",username);
printf("\nPassword:");
scanf("%s",pass);
signIn(username, pass);
}
if(choose==2) {
signUp(username, pass, fullName);
}
}
I tried a lot different ways and i'm really confused right now..
scanf("%s", &username); is not correct. It shall be scanf("%s", &username[0]); One should give concentration to the warnings especially for array/pointers involved.
Similarly below 2 lines
scanf("%s", &pass[0]);
scanf("%s", &fullName[0]);
fprintf(p, "%s\n%s\n%s", username, fullName, pass); You writing the fullname as second line, but while reading, you read 2nd line as password. So fprintf(p, "%s\n%s\n%s", username, pass,fullName );
Another suggestion, after opening the file, the file pointer shall be checked for its validity. for some reason, if it returns NULL, then your program would crash.
Instead of simply trying compiling and getting the o/p, best way to debug this simple code is to sit down with pen and paper, try analyse what happens with each line
A number of things that are wrong with your code jumped out at me. I tried to fix as much as I could. The following should work.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int signIn(char username[], char pass[]) {
FILE *p;
char user2[30], pass2[30], fullName[50];
if (!(p = fopen("users.txt", "r+"))) {
printf("Could not read from users.txt file\n");
fclose(p);
return 1;
}
int ret = 2;
while (fgets(user2, 30, p) != NULL) {
fgets(pass2, 30, p);
fgets(fullName, 50, p);
// you have written the fullName to the file as a third line, so you must check for this too
if ((strcmp(username, user2) == 0) && (strcmp(pass, pass2) == 0)) {
printf("\nUser and password correct!!!\n");
printf("Logged in as %s", fullName);
ret = 0;
break;
}
}
if (ret == 2)
printf("\nUser or password incorrect!\n");
printf("\n\n");
fclose(p);
return ret;
}
int signUp(void) {
FILE *p;
char username[30], pass[30], fullName[50];
if (!(p = fopen("users.txt", "w+"))) {
printf("Could not write to users.txt file\n");
fclose(p);
return 1;
}
printf("Username: ");
fgets(username, 30, stdin);
printf("Password: ");
fgets(pass, 30, stdin);
printf("Full name: ");
fgets(fullName, 50, stdin);
fprintf(p, "%s%s%s", username, pass, fullName);
printf("You have signed up!\n");
fclose(p);
return 0;
}
int main(void) {
char username[30], pass[30];
int choose;
printf("Welcome to student login system!\n");
printf(" 1: Sign in\n 2: Sign up\n");
printf("--------------------------------\n");
scanf("%d", &choose);
getchar();
if (choose == 1) {
printf("User: ");
fgets(username, 30, stdin);
printf("Password: ");
fgets(pass, 30, stdin);
return signIn(username, pass);
}
else if (choose == 2) {
return signUp();
}
return 0;
}
EDIT: I apologize for the sloppy answer, I was not on my main computer. This code will work for reading 1 user.