I'm doing my bank record management system project and I'm facing problem in reading from file. My file name is "name_of_the_user.txt" and opened in wb+ mode. I've a structure which have some fields such as name, address, money, etc. I've been trying to deposit and withdraw from account by reading the data into structure BMS u1 and then doing following functions, but I think reading into this structures leads to corruption of file and some garbage value. Please help.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
void main_menu(char*);
void update_acc(char *);
// void deposit( char *);
// void withdrawl( char *);
struct BMS
{
char name[20];
char mailid[20];
unsigned long long contact;
unsigned long long adhar;
int date, year, month;
char address[100];
char password[15];
int money;
};
struct balance{
char namefrom[20];
char nameto[20];
long int money;
};
void gotoxy(int x, int y)
{
COORD c;
c.X = x;
c.Y = y;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void view_acc(char username[])
{
FILE *fp;
struct BMS u1;
char filename[20];
strcpy(filename, username);
fp = fopen(strcat(filename, ".bin"), "rb");
if(fp==NULL){
printf("Error viewing account details.");
}
fread(&u1, sizeof(u1), 1, fp);
printf("%s\n", u1.name);
printf("%llu\n", u1.contact);
printf("%llu\n", u1.adhar);
printf("%d - %d - %d\n", u1.date, u1.month, u1.year);
printf("%s\n", u1.address);
printf("%s\n", u1.mailid);
printf("Balance : %d\n", u1.money);
fclose(fp);
}
void create_acc()
{
system("cls");
FILE *fp;
struct BMS u1;
int k=0;
char ch1, temp, filename[20];
scanf("%c",&temp);
u1.money = 0;
printf("\t\t\tFill in the details \n");
printf("Name of account holder: ");
scanf("%[^\n]", &u1.name);
printf("Enter DOB : ");
printf("Date : ");
scanf("%d" , &u1.date);
printf("\nMonth : ");
scanf("%d", &u1.month);
printf("\nYear : ");
scanf("%d", &u1.year);
printf("Enter your mobile number : ");
scanf("%llu", &u1.contact);
printf("Enter your Aadhar ID : ");
scanf("%llu", &u1.adhar);
scanf("%c",&temp);
printf("Enter user email : ");
scanf("%[^\n]", &u1.mailid);
scanf("%c",&temp);
printf("Enter Your Address : ");
scanf("%[^\n]", &u1.address);
printf("Create PIN : ");
for(k=0; k<15; k++)
{
ch1 = getch();
u1.password[k]=ch1;
if(ch1!=13 && ch1!=8)
printf("*");
if(ch1 == 13)
break;
}
u1.password[k]='\0';
printf("\nYour created PIN is : ");
for(k=0; k<strlen(u1.password); k++){
printf("%c", u1.password[k]);
}
printf("\nYour Account has beem succesfully added to our system. Please remember your created PIN to acces your account.\n\n");
strcpy(filename, u1.name);
fp = fopen(strcat(filename, ".bin"), "ab");
fwrite(&u1, sizeof(u1),1, fp);
fclose(fp);
}
void login(){
system("cls");
FILE *fp;
struct BMS u1;
char name[20], temp, password[15],ch1, filename[20];
int i, j, k;
scanf("%c",&temp);
printf("Enter your name : ");
scanf("%[^\n]", &name);
scanf("%c",&temp);
printf("Enter your PIN : ");
scanf("%s", &password);
strcpy(filename, name);
fp = fopen(strcat(filename, ".bin"),"rb");
if(fp==NULL){
printf("No account found.");
}
fread(&u1, sizeof(u1), 1, fp);
if(!strcmp(password, u1.password)){
printf("Login succesful.");
fclose(fp);
main_menu(name);
}
else {
printf("Login failed wrong password.");
fclose(fp);
}
}
void transaction(char username[])
{
system("cls");
FILE *fp, *fp1, *fm;
struct BMS u1;
struct balance b1;
char userfrom[20], userto[20],username1, username2, temp;
// strcpy(username1, username);
scanf("%c", &temp);
printf("Transfer money to : ");
scanf("%[^\n]", &userto);
printf("Enter the amount to be transferred : ");
scanf("%ld", &b1.money);
// fp1 = fopen(strcat(username1, ".txt"), )
strcpy(userfrom, username);
strcpy(username, userto);
fp = fopen(strcat(username, ".bin"), "rb");
fm = fopen("money.bin", "ab");
while (fread(&u1, sizeof(u1), 1, fp))
{
if (strcmp(userto, u1.name) == 0) {
strcpy(b1.nameto, u1.name);
strcpy(b1.namefrom, userfrom);
}
}
fwrite(&b1, sizeof(b1), 1, fm);
fclose(fm);
fclose(fp);
}
void viewbalance(char username[]){
system("cls");
FILE *fm;
struct balance b1;
char ch;
int i=1 , money=0;
fm = fopen("money.bin", "rb");
int k = 5, l = 10;
int m = 30, n = 10;
int u = 60, v = 10;
gotoxy(30, 2);
printf("==== BALANCE DASHBOARD ====");
gotoxy(30, 3);
printf("***************************");
gotoxy(k, l);
printf("S NO.");
gotoxy(m, n);
printf("TRANSACTION ID");
gotoxy(u, v);
printf("AMOUNT");
while (fread(&b1, sizeof(b1), 1, fm)) {
if (strcmp(username, b1.nameto) == 0) {
gotoxy(k, ++l);
printf("%d", i);
i++;
gotoxy(m, ++n);
printf("%s", b1.namefrom);
gotoxy(u, ++v);
printf("%ld", b1.money);
money = money + b1.money;
}
}
gotoxy(80, 10);
printf("TOTAL AMOUNT");
gotoxy(80, 12);
printf("%d", money);
getch();
fclose(fm);
}
void deposit( char username[]){
struct BMS u1;
FILE *fp;
char filename[20];
strcpy(filename, username);
fp = fopen(strcat(filename, ".bin"), "wb+");
fread(&u1, sizeof(u1),1, fp);
int amount = 0;
printf("Enter the amount to be deposited : ");
scanf("%d", &amount);
u1.money = u1.money + amount;
printf("Money succesfully deposited.");
fseek(fp, 0, SEEK_SET);
fwrite(&u1, sizeof(u1),1, fp);
fclose(fp);
}
void withdrawl( char username[]){
struct BMS u1;
FILE *fp;
char filename[20];
strcpy(filename, username);
fp = fopen(strcat(filename, ".bin"), "wb+");
if(fp==NULL){
printf("Error");
}
printf("%s", u1.name);
if(fread(&u1, sizeof(u1),1, fp)!=0){
printf("error");
}
printf("%s", u1.name);
int amount = 0;
printf("Enter the amount to be withdrawn : ");
scanf("%d", &amount);
// fread(&u1, sizeof(u1), 1, fbin
if(u1.money<amount){
printf("Not enough money to withdraw.\n");
}
else{
u1.money = u1.money - amount;
printf("Money succesfully withdrawn.\n");
fseek(fp, 0, SEEK_SET);
fwrite(&u1, sizeof(u1),1, fp);
}
fclose(fp);
}
void main_menu(char username[]){
system("cls");
char username1[20];
strcpy(username1, username);
while(1){
printf("\t\t\t\tWELCOME %s\n", username);
printf("\t\t\t\t1.View account details\n");
printf("\t\t\t\t2.Update Account\n");
printf("\t\t\t\t3.Make a Transaction\n");
printf("\t\t\t\t4.To view all Transaction\n");
printf("\t\t\t\t5.Make a Deposit\n");
printf("\t\t\t\t6.Make a Withdrawl\n");
printf("\t\t\t\t7.LOG OUT\n");
int ch;
printf("Enter your choice : ");
scanf("%d", &ch);
if(ch==1){
view_acc(username1);
}
else if(ch==2){
update_acc(username1);
}
else if(ch==3){
transaction(username1);
}
else if(ch==4){
viewbalance(username1);
}
else if(ch==5){
deposit(username1);
}
else if(ch==6){
withdrawl(username1);
}
}
}
void update_acc(char username[]){
FILE *fp1, *fp2;
struct BMS u1;
struct BMS u2;
int ch, k=0;
char temp, ch1, filename[20];
strcpy(filename, username);
fp1 = fopen(strcat(filename, ".bin"), "rb");
fp2 = fopen("copy.bin", "ab");
if(fp1==NULL){
printf("error updating data!\n");
}
printf("Press 1 to update Name.\n");
printf("Press 2 to update Mobile number.\n");
printf("Press 3 to update Email id.\n");
printf("Press 4 to update Address.\n");
printf("Press 5 to update DOB.\n");
printf("Press 6 to update password.\n");
printf("Press 0 to go back\n");
printf("Enter your choice : ");
scanf("%d", &ch);
if(ch==1){
printf("Please enter your new name : ");
char name[20];
scanf("%d", &temp);
scanf("%[^\n]", &name);
while(fread(&u1, sizeof(u1), 1, fp1)){
if(strcmp(u1.name , name)){
fwrite(&u1, sizeof(u1), 1, fp2);
}
}
strcpy(u2.name , name);
fwrite(&u2, sizeof(u2), 1, fp2);
fclose(fp2);
fclose(fp1);
int del = remove(filename);
rename("copy.bin", filename);
printf("Name succesfully updated.\n");
}
else if(ch==2){
printf("Please enter your new mobile number : ");
unsigned long long contact;
scanf("%llu", &contact);
while(fread(&u1, sizeof(u1), 1, fp1)){
if(u1.contact != contact){
fwrite(&u1, sizeof(u1), 1, fp2);
}
}
u2.contact = contact;
fwrite(&u2, sizeof(u2), 1, fp2);
fclose(fp2);
fclose(fp1);
int del = remove(filename);
rename("copy.bin", filename);
printf("Contact succesfully updated.\n");
}
else if(ch==3){
printf("Please enter your new mail id : ");
scanf("%d", &temp);
char mailid[20];
scanf("%[^\n]", &mailid);
while(fread(&u1, sizeof(u1), 1, fp1)){
if(strcmp(u1.mailid , mailid)){
fwrite(&u1, sizeof(u1), 1, fp2);
}
}
strcpy(u2.mailid , mailid);
fwrite(&u2, sizeof(u2), 1, fp2);
fclose(fp2);
fclose(fp1);
int del = remove(filename);
rename("copy.bin", filename);
printf("Email succesfully updated.\n");
}
else if(ch==4){
printf("Please enter your new address : ");
scanf("%d", &temp);
char address[100];
scanf("%[^\n]", &address);
while(fread(&u1, sizeof(u1), 1, fp1)){
if(strcmp(u1.address , address)){
fwrite(&u1, sizeof(u1), 1, fp2);
}
}
strcpy(u2.address , address);
fwrite(&u2, sizeof(u2), 1, fp2);
fclose(fp2);
fclose(fp1);
int del = remove(filename);
rename("copy.bin", filename);
printf("Address succesfully updated.\n");
}
else if(ch==5){
printf("Enter your new DOB : ");
int date, month, year;
printf("Date : ");
scanf("%d" , &date);
printf("\nMonth : ");
scanf("%d", &month);
printf("\nYear : ");
scanf("%d", &year);
while(fread(&u1, sizeof(u1), 1, fp1)){
if(u1.date != date || u1.month != month || u1.year != year){
fwrite(&u1, sizeof(u1), 1, fp2);
}
}
u2.date = date;
u2.month = month;
u2.year = year;
fwrite(&u2, sizeof(u2), 1, fp2);
fclose(fp2);
fclose(fp1);
int del = remove(filename);
rename("copy.bin", filename);
printf("DOB succesfully updated.\n");
}
else if(ch==6){
printf("Enter your new PIN : ");
char password[15];
for(k=0; k<15; k++){
ch1 = getch();
password[k]=ch1;
if(ch1!=13 && ch1!=8)
printf("*");
if(ch1 == 13)
break;
}
password[k]='\0';
printf("\nYour new created PIN is : ");
for(k=0; k<strlen(password); k++){
printf("%c", password[k]);
}
while(fread(&u1, sizeof(u1), 1, fp1)){
if(strcmp(u1.password , password)){
fwrite(&u1, sizeof(u1), 1, fp2);
}
}
strcpy(u2.password , password);
fwrite(&u2, sizeof(u2), 1, fp2);
fclose(fp2);
fclose(fp1);
int del = remove(filename);
rename("copy.bin", filename);
printf("\nPassword succesfully updated.\n");
}
else if(ch==0){
fclose(fp1);
fclose(fp2);
}
}
// void deposit( char username[]){
// struct BMS u1;
// FILE *fp;
// char filename[20];
// strcpy(filename, username);
// fp = fopen(strcat(filename, ".txt"), "w+");
// fread(&u1, sizeof(u1),1, fp);
// int amount = 0;
// printf("Enter the amount to be deposited : ");
// scanf("%d", &amount);
// u1.money = u1.money + amount;
// printf("Money succesfully deposited.");
// fwrite(&u1, sizeof(u1),1, fp);
// fclose(fp);
// }
// void withdrawl( char username[]){
// struct BMS u1;
// FILE *fp;
// char filename[20];
// strcpy(filename, username);
// fp = fopen(strcat(filename, ".txt"), "w+");
// fread(&u1, sizeof(u1),1, fp);
// int amount = 0;
// printf("Enter the amount to be withdrawn : ");
// scanf("%d", &amount);
// fread(&u1, sizeof(u1), 1, fp);
// if(u1.money<amount){
// printf("Not enough money to withdraw.");
// }
// else{
// u1.money = u1.money - amount;
// printf("Money succesfully withdrawn.");
// fwrite(&u1, sizeof(u1),1, fp);
// }
// fclose(fp);
// }
int main()
{
system("cls");
struct BMS u1[N];
int choice;
int i = 0;
while (5)
{
printf("\t\t\t\tWELCOME TO THE BANK MANAGEMENT SYSTEM\n");
printf("\t\t\t\t1.Create new account\n");
printf("\t\t\t\t2.Login into existing account\n");
printf("\t\t\t\t6.Exit\n");
printf("\nEnter Your Choice : ");
scanf("%d", &choice);
if (choice == 1)
{
create_acc();
}
else if (choice == 2)
{
login();
}
else if (choice == 6){
}
}
//printf("Thanks For Coming !!");
return 0;
}
You need to seek to the beginning of the file before you write. Otherwise it writes the updated record at the place where you left off reading, instead of overwriting the original record.
void deposit( char username[]){
struct BMS u1;
FILE *fp;
char filename[20];
strcpy(filename, username);
fp = fopen(strcat(filename, ".txt"), "wb+");
fread(&u1, sizeof(u1),1, fp);
int amount = 0;
printf("Enter the amount to be deposited : ");
scanf("%d", &amount);
u1.money = u1.money + amount;
printf("Money succesfully deposited.");
fseek(fp, 0, SEEK_SET);
fwrite(&u1, sizeof(u1),1, fp);
fclose(fp);
}
First, the while loop is not comparing titles in the file and the num_books does not add on top of the file. Second, instead of reading the num_books already in the file, it reads twice every time executed. can someone help?
typedef struct book {
char *title;
char *author;
char *subject;
};
struct library {
struct book collection;
int num_books;
struct library *next;
};
add(FILE *file, FILE *fileout, struct library *thislib, struct book *thisbook) {
char choice = "1";
int size;
char line1[50];
file = fopen("temp1.txt", "a+");
fileout = fopen("temp2.txt", "a+");
printf("\t Add a book to your library!\n");
printf("\t\t Title: ");
scanf("%s", &thisbook->title);
printf("\t\t Author: ");
scanf("%s", &thisbook->author);
printf("\t\t Subject: ");
scanf("%s", &thisbook->subject);
fseek(file, 0, SEEK_SET);
thislib->num_books++;
fprintf(file, "%d", thislib->num_books);
size = ftell(file);
while (thislib->num_books > 1) {
for (int i = 1; i < size; i++) {
fseek(file, i, SEEK_CUR);
fscanf(file, "%s", line1);
printf("%s", line1);
if (strcmp(thisbook->title, line1) != 0) {
printf("Please re-enter title as similar ones are not allowed.\n");
printf("\t\t Title: ");
scanf("%s", &thisbook->title);
strcpy(line1, "");
}
}
}
fseek(file, 1, SEEK_SET);
fprintf(file, "%c %s %s %s\n", choice, &thisbook->title, &thisbook->author, &thisbook->subject);
fprintf(fileout, "The book %s, author %s, subject %s has been added to the library.\n", &thisbook->title, &thisbook->author, &thisbook->subject);
fclose(file);
fclose(fileout);
}
I need to solve a problem. I need to create two functions which scan user's input information and put in into structure array and then put all array to BIN file (with function fwrite()) and other function - read from BIN file with function fread(). You can see my code below. Problem is that I can write to file, but when I read I get filler array element and other element which are empty. How to get only filled struct array element?
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
typedef struct
{
char Lesson[50];
char TeachersName[50];
char TeachersLastName[50];
int Credits;
int NumberOfStudents;
} School;
void ToFile (char *fileName);
void FromFile (char *FileName);
int main()
{
char *fileName[]={"student.bin"};
ToFile (*fileName);
FromFile (*fileName);
return 0;
}
void ToFile (char *fileName)
{
int n, chars;
FILE *fp;
fp = fopen(fileName, "wb");
School Info[20];
if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fwrite() function: \n\n");
printf("Enter the number of records you want to enter: ");
scanf("%d", &n);
for(int i = 0;i<n;i++)
{
printf("\nEnter details of employee %d \n", i + 1);
fflush(stdin);
printf("Lesson: ");
gets(Info[i].Lesson);
printf("Teachers name: ");
gets(Info[i].TeachersName);
printf("Teachers last name: ");
gets(Info[i].TeachersLastName);
printf("Credits: ");
scanf("%d", &Info[i].Credits);
printf("Number of studens: ");
scanf("%d", &Info[i].NumberOfStudents);
chars = fwrite(&Info[i], sizeof(Info), 1, fp);
printf("Number of items written to the file: %d\n", chars);
}
fclose(fp);
}
void FromFile (char *FileName)
{
School Info[20]= { { "", "","",0,0 } };;
FILE * fpp;
fpp = fopen(FileName, "rb");
fread(&Info, sizeof(Info), 1, fpp);
/*
for(int j=0; j<20; ++j) {
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
}*/
int j=0;
while (fread(&Info, sizeof(Info), 1, fpp))
{
printf("\nLesson: %s", Info[j].Lesson);
printf("\nTeachers name: %s", Info[j].TeachersName);
printf("\nTeachers last name: %s", Info[j].TeachersLastName);
printf("\nCredits: %d", Info[j].Credits);
printf("\nNumber of students: %d", Info[j].NumberOfStudents);
printf("\n");
j++;
}
fclose(fpp);
}
In the code below I'm trying to insert, display and delete data from a file.txt. I'm being able to insert successfully but my display function do not display correct and I don't know how to set up the logic to make the delete function. I would appreciate some help in changing the code so it can works. How can I set up the logic for it?
#include <stdio.h>
void menu() {
printf("Option 1 - Create a file and insert data:\n");
printf("Option 2 - Read file and display:\n");
printf("Option 3 - Delete content:\n");
printf("Option 4 - Exit:\n");
};
struct Book {
char title[256];
char author[256];
int pages;
int price;
};
void get() {
struct Book *book;
book = (struct Book*)malloc(sizeof(struct Book));
FILE *fPtr;
fPtr = fopen("file.txt", "w");
if (fPtr == NULL) {
printf("Fail creating file");
getch();
exit(1);
};
for (int i = 0; i < 1; i++) {
printf("Enter the book title:\n");
scanf("%s", &book[i].title);
fprintf(fPtr, "Title = %s", book[i].title);
printf("Enter the author of the book:\n");
scanf("%s", &book[i].author);
fprintf(fPtr, "Author = %s", book[i].author);
printf("Enter the number of pages:\n");
scanf("%d", &book[i].pages);
fprintf(fPtr, "Pages = %d", book[i].pages);
printf("Enter the price:\n");
scanf("%d", &book[i].price);
fprintf(fPtr, "Price = %d", book[i].price);
};
/*for (int i = 0; i < 1; i++) {
printf("%s\n", book[i].title);
printf("%s\n", book[i].author);
printf("%d\n", book[i].pages);
printf("%d\n", book[i].price);
};*/
fclose(fPtr);
};
void display() {
FILE *fPtr;
fPtr = fopen("file.txt", "r");
printf("The content of file are:\n", fPtr);
/*struct Book *book;
book = (struct Book*)malloc(sizeof(struct Book));
printf("%s %s %d %d", book.title, book.author, book.pages, book.price);*/
free(book);
fclose(fPtr);
}
int main()
{
int opt = 0;
int opt2 = 0;
int var = 0;
int validation = 0;
while (opt != 4) {
menu();
do
{
printf("Choose an option:\n");
validation = scanf_s("%d", &opt);
while (getchar() != '\n');
} while (validation != 1);
switch (opt) {
case 1:
get();
printf("Option 5 - Display data:\n");
printf("Option 6 - Delete:\n");
scanf("%d", &var);
if (var == 5) {
//FILE *fp1;
/*fp1 = fopen("file.txt", "r");*/
display();
}
else if (var == 6) {
printf("delete!");
}
break;
case 2:
printf("First insert data:\n");
break;
case 3:
printf("First insert data:\n");
break;
case 4:
return 0;
}
}
}
note : display() proposal 2
void display() {
FILE *fp;
fp = fopen("file.txt", "r");
struct Book book;
printf("%s %s %d %d", book.title, book.author, book.pages, book.price);
free(book);
fclose(fp);
}
I encourage you to rename Books to Book because that struct manages one book, not several.
About the command codes to enter, rather than 1 .. 4 what about 'c' for create, 'r' for read, 'd' for delete and 'e' for exit ?
Concerning get() :
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0, do you really manages only 1 book ?
in your fprintf move the '\n' from the beginning to the end, else your file starts by an empty line and the last line is not ended
Is it necessary to prefix each data by its kind like Title = ? To read the file content is more complex with these prefixes
Concerning display() :
you do not read the content of the file, so difficult do display it :)
you allocate a Books, do not initialize it, but write its( uninitialized) fields
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
Concerning display() :
you do not read the content of the file, so difficult do display it :)
you allocate a Books, do not initialize it, but write its( uninitialized) fields
for (int i = 0; i < 1; i++) is useless and equivalent to int i = 0
you have a memory leak because the allocated Books is not freed. This allocation is useless, better to have struct Book book;
Concerning deleteStudentRecord() :
getNoOfRecords() is not defined, but currently it must return 1 because you manage only one book in the file
var is not defined, nor ptr
open file2 with "w", it is a new file
fread(&var, sizeof(struct student), 1, ptr) is wrong because it supposes a line has always sizeof(struct student) but this is not the case refering to get()
fcloseall() ??? just do fclose(ptr); and fclose(ptr2), rename them fpIn and fpOut or something like will make your code more readable
"get(); proposal 2"
void get() {
FILE *fPtr;
fPtr = fopen("file.txt", "w");
struct Book book;
if (fPtr == NULL) {
printf("Fail creating file");
getch();
exit(1);
};
printf("Enter the book title:\n");
scanf("%s", &book.title);
fprintf(fPtr, "%s", book.title);
printf("Enter the author of the book:\n");
scanf("%s", &book.author);
fprintf(fPtr, "%s", book.author);
printf("Enter the number of pages:\n");
scanf("%d", &book.pages);
fprintf(fPtr, "%d", book.pages);
printf("Enter the price:\n");
scanf("%d", &book.price);
fprintf(fPtr, "%d", book.price);
/*for (int i = 0; i < 1; i++) {
printf("%s\n", book[i].title);
printf("%s\n", book[i].author);
printf("%d\n", book[i].pages);
printf("%d\n", book[i].price);
};*/
fclose(fPtr);
};