How to edit a file in C? - c

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");
^

Related

C program to get user input and validate from .dat FILES

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");
}
}

How to deal with different set of questions for verification in C?

There are some problems in this code which I am unable to figure it out. No.1 is with printf() which is just allowing me to enter name but date of birth. No.2 is maybe the the problem with if statement. No. 3 is that the else statement just stops the process but didn't show me the message.
int list_view(char *name, char *dob, char *id, char *phone_num, char *address, char *account, char *fixing, char *amount){
printf("To show you details, please enter the person name and id card number: \n");
printf("Enter your Name: ");
printf("Enter you Date of Birth: ");
if(fgets(name, sizeof name, stdin) && fgets(dob, sizeof dob, stdin)){
FILE * fr;
int one_by_one;
fr = fopen("/home/bilal/Documents/file.txt", "r");
for (int i=0; i<8; i++){
printf("\nHere is your "); /* listing is transferred above just to show ones */
while((one_by_one = fgetc(fr)) != EOF && one_by_one != '\n'){
printf("%c",one_by_one); /* display on screen*/
}
} /* end of for loop */
fclose(fr);
} /* end of if statement */
else{
printf("No access");
}
return 0;
}
First you should prompt and get each piece of input in turn. ie
printf("Enter your Name: ");
fgets(name, sizeof name, stdin); /// with some checking
printf("Enter you Date of Birth: ");
fgets(dob, sizeof dob, stdin); // with some checking
second,
sizeof name
is useless, its the size of a pointer. If these input buffers are supplied by the caller then they have to pass in a buffer size arg too.
You seem hung up on your 'if'.
This is what you need I think. If they dont enter a value for either prompt then you want to say 'no access' and return
printf("Enter your Name: ");
if(!fgets(name, namesize, stdin))
{
printf("no access");
return;
}
printf("Enter you Date of Birth: ");
if(!fgets(dob, dobsize, stdin))
{
printf("no access");
return;
}

How to edit data of a file File Handling C

I'm wondering if I could use fseek() on editing the value of a variable on a file. All the tutorials I saw online were about editing a text, but how can I use fseek() to edit a value.
Here's how my program works: The user inputs a name, gender, and age. The user can input as many data as they want. Now, the user searches a name; and the gender, and age of that name will display. The user is then prompted to edit the age. After inputting a new age, the file will now be edited, with the new age written.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data
{
char name[30];
char gender[10];
int age;
};
int main(void)
{
struct data client;
FILE* fp;
char ch = 0;
do
{
printf("Enter Name: ");
scanf("%s", client.name);
printf("Enter Gender: ");
scanf("%s", client.gender);
printf("Enter Age: ");
scanf("%d", &client.age);
fp = fopen("data.txt", "ab");
fwrite(&client, sizeof(client), 1, fp);
fclose(fp);
printf("continue? \n");
scanf(" %c", &ch);
} while (ch != 'n'); // continuously appends file till letter n is read;
char input[30]; // user input
printf("name?\n");
scanf("%s", input);
struct data Read;
fp = fopen("data.txt", "rb");
int newAge;
while (fread(&client, sizeof(client), 1, fp))
{
if (strcmp(client.name, input) == 0) // compare variable with user input
{
printf("%s", client.name);
printf(" %s", client.gender);
printf(" %d y/o", client.age);
printf("\n");
printf("enter new age");
scanf("%d", &newAge);
//fseek function
}
}
return 0;
}
Hope somebody can help.

Error while sign up in simple file login program

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.

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.

Resources