I am a relatively new programmer currently learning the C language at college. For my project I have been tasked to design a library system for students, I have been experiencing a debug assertion failed-error whenever I try to delete the same book that has been recently edited. Can somebody help me on this question?
PS: I have to submit the program in a few days' time, so I need some help! D:
Here's my code for editing books:
void EditBookInformation()
{
int found = 0;
char user_input[5];
system("cls");
printf("You have selected Edit Book Information \n");
printf("Please enter the Book ID to edit the book: \n");
scanf_s(" %s", &user_input, 5);
fflush(stdin);
fopen_s(&BookList, "record.txt", "rb+");
fopen_s(&BookList2, "newrecord.txt", "wb+");
fopen_s(&Logsheet, "log.txt", "a+");
rewind(BookList);
rewind(BookList2);
while (fread(&Books, sizeof(Books), 1, BookList) != NULL)
{
if (strcmp(user_input, Books.Book_ID) == 0)
{
found = 1;
printf("Book has been found! \n");
printf("\nBook ID:%s \n", Books.Book_ID);
printf("Title:%s \n", Books.Title);
printf("Edition:%s \n", Books.Edition);
printf("Year of publication:%s \n", Books.Year_of_publication);
printf("Shelf location:%s \n", Books.Shelf_location);
printf("Price in RM:%s \n", Books.Price);
break;
}
else
{
fwrite(&Books, sizeof(Books), 1, BookList2);
}
}
if (!found)
{
printf("Book not found! \n");
_fcloseall();
system("pause");
system("cls");
main();
}
char confirm;
printf("\nDo you want to edit this book?");
scanf_s("%c", &confirm);
fflush(stdin);
if (confirm == 'y')
{
printf("New Title:");
scanf_s("%[^\n]s", &Books.Title, 50);
while (getchar() != '\n');
printf("New Edition:");
scanf_s("%s", &Books.Edition, 6);
while (getchar() != '\n');
NewYearInput:
printf("New Year of publication:");
scanf_s("%s", &Books.Year_of_publication, 5);
while (getchar() != '\n');
int length = strlen(Books.Year_of_publication);
int digit = 0;
if (length == 4)
{
for (; digit < length; digit++)
if (!isdigit(Books.Year_of_publication[digit]))
break;
}
if (digit != 4)
{
printf("Wrong input! Please enter 4 digits for year! \n");
system("pause>nul");
goto NewYearInput;
}
printf("New Shelf Location:");
scanf_s("%s", &Books.Shelf_location, 5);
while (getchar() != '\n');
printf("New Price in RM:");
scanf_s("%s", &Books.Price, 5);
while (getchar() != '\n');
fprintf(Logsheet, "Book edited: %s \n", Books.Title);
fseek(BookList, ftell(BookList) -sizeof(Books), SEEK_SET);
fwrite(&Books, 1, sizeof(Books), BookList);
fclose(BookList);
fclose(Logsheet);
printf("Book has been edited! \n");
printf("Press any key to return to main menu \n");
system("pause>nul");
system("cls");
main();
}
else if (confirm == 'n')
{
printf("You have cancelled your operation! \n");
_fcloseall();
system("cls");
main();
}
}
And here is my code for deleting books:
void DeleteBookByBookID()
{
int found = 0;
char user_input1[5];
system("cls");
printf("You have selected Delete Book \n");
printf("Please enter the Book ID that you want to delete the book \n");
scanf_s("%s", &user_input1, 5);
fflush(stdin);
fopen_s(&BookList, "record.txt", "rb+");
fopen_s(&BookList2, "newrecord.txt", "wb+");
fopen_s(&Logsheet, "log.txt", "a+");
rewind(BookList);
rewind(BookList2);
while (fread(&Books, sizeof(Books), 1, BookList) != NULL)
{
if (strcmp(user_input1, Books.Book_ID) == 0)
{
printf("Book found! \n");
found = 1;
}
else
{
fwrite(&Books, sizeof(Books), 1, BookList2);
}
}
if (!found)
{
printf("Book ID not found! \n");
_fcloseall();
system("pause");
system("cls");
main();
}
fclose(BookList);
fclose(BookList2);
char confirm;
printf("Do you want to delete this book? \n");
scanf_s(" %c", &confirm);
fflush(stdin);
if (confirm == 'y')
{
remove("record.txt");
rename("newrecord.txt", "record.txt");
fprintf(Logsheet, "Book deleted: %s \n", Books.Title);
printf("Book has been deleted! \n");
printf("Press any key to return to main menu \n");
system("pause>nul");
system("cls");
main();
}
else if (confirm == 'n')
{
printf("You have cancelled your operation! \n");
fclose(BookList);
fclose(BookList2);
system("cls");
main();
}
fclose(Logsheet);
}
If a book is not found, you are calling main. But main should not be called by the user. It is called by the system and is the start of your program. Maybe you mean return?
You are reading from BookList and if the record read is not the one you want, you write it to BookList2. Once the record is found, you edit it and then write it to BookList2 and then you close the files and rename the new file to the old file. But what happens to all the remaining records in the old file? Shouldn't you copy those too to the new file?
See also the comments to your post for other helpful sugestions.
Related
So I have this code:
printf("S: Search\n");
printf("A: Add\n");
printf("D: Delete\n");
printf("Q: Quit\n");
printf("\nYour choice: ");
while (fgets(line, MAXLINE, stdin) && once == 1)
{
printf("Option: %s\n", line);
once++;
}
And here comes where I'm struggling:
if (line == 's')
{
printf("option s function here");
} else if (line == 'a')
{
printf("option a function here...");
} /* and so on */
This is not working and I've been trying to fix it but nothing I tried worked. How can I write that last piece of code in order to be able to select an option from the fgets input?
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 am using "dev cpp" and i'm writing some codes in c
While I'm running the code below, after entering all data in the function 1, the exe file just crash.
there are not error shown before i finish entering all the data ad press enter
What is happening?
// hotel system *work in progress*//
#include<stdio.h>
#include<stdlib.h>
struct book
{
int bookno[20];
char travellername[20];
char destination[20];
char hotelname[20];
char checkin[20];
char checkout[20];
int guestno[20];
char type[20];
float fee;
}b;
void add();//Add new booking
void all(); //view all booking
//void mod(); modify booking
//void search(); search booking
//void del(); delete booking
void main()
{
int choose;
do{
printf("\n *** Welcome to Hong Kong Hotek booking Record and Management System 2017 ***\n");
printf("\n *** This system is developed by CCIT4020 Class No.NL-?? Group No.?? ***");
printf("\n\n\n--<Basic functions>-- \n");
printf("\n1. Add New Hotel Booking Record(s): \n");
printf("\n2. Display All Hotel Booking Records: \n");
printf("\n3. Modify Hotel Booking Record(s): \n");
printf("\n4. Search Hotel Booking Record(s): \n");
printf("\n5. Delete Hotel Booking Record(s): \n");
printf("\n0. Quit: \n");
printf("\nWhat is your option (0-5)? ");
scanf("%d",&choose);
switch (choose)
{
case 1 :
add();
break;
case 2:
all();
break;
//case 3:
// mod();
//break;
//case 4:
// search();
//break;
//case 5:
// del();
//break;
case 0:
exit(0);
break;
default:
printf("Invalid choice! Please enter again!");
break;
}
}while(choose!=0);
}
void add()
{
FILE *fp;
struct book b;
printf("Hotel Booking number: ");
scanf("%s",b.bookno);
printf("Name of Traveller: ");
scanf("%s",b.travellername);
printf("Destination: ");
scanf("%s",b.destination);
printf("Name of Hotel: ");
scanf("%s",b.hotelname);
printf("Check-in Schedule: ");
scanf("%s",b.checkin);
printf("Check-out Schedule: ");
scanf("%s",b.checkout);
printf("Number of Guests: ");
scanf("%s",b.guestno);
printf("Room Type: ");
scanf("%s",b.type);
printf("Total Fee: ");
scanf("%s",b.fee);
fp=fopen("data.txt","a");
if(fp == NULL)
{
printf("There are no data file! please create one!");
}
else
{
fprintf(fp,"%s \n %s \n %s \n %s \n %s \n %s \n %s \n %s \n %s",b.bookno,b.travellername,b.destination,b.hotelname,b.checkin,b.checkout,b.guestno,b.type,b.fee);
printf("One Record Added!");
}
printf("\n");
fclose(fp);
}
void all()
{
char choose;
FILE *fp;
fp = fopen("data.txt","r");
if(fp == NULL)
{
printf("There are no data file!");
exit(1);
}
else
{
system("clear");
while( ( choose = fgetc(fp) ) != EOF )
printf("%c",choose);
}
fclose(fp);
}
Read your compiler messages:
The problem is here:
scanf("%s",b.fee);
The format specifier is %s, but b.fee is a float.
You need this:
scanf("%f", &b.fee);
There are likely more problems like that one. Check them out by yourself. Each scanfformat specifier must match the variable.
I've made this program for a school project. It runs just fine except that I'm unable to write the data in text file as I desire. The file text that i get is as follows :
AJames y$¥ °› †løvúövÿÿÿÿ$ „þB-28 ®kt¼› €# ° # ¬þ …tt¸?’tìþ¢it Mark $¥€# €# ° # Àþ øþÌÿ IT tÕÑþÿÿÿ áD
I'm not strong in C and therefore, even after going through online forums, I'm unable to find a specific answer. The following is the code :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
#include<string.h>
int main()
{
FILE *fp, *ft;
char tmp, choice;
struct fee
{ float r_no;
char name[50];
char add[50];
char f_name[40];
char stream[10];
float d_fee;
}f;
long int amount;
int flag;
long int total = 2000;
long int pending=0;
long int size;
char stream1[40];
float r_no1;
fp=fopen("FEES.txt","w");
if(fp==NULL)
{
puts("Cannot open file");
exit(1);
}
size = sizeof(f);
while(1)
{
system("cls");
printf("\n\t\tWelcome to Main Menu!!");
printf("\n\t\t1. Student Detail");
printf("\n\t\t2. Display Record");
printf("\n\t\t3. Deposit Fee");
printf("\n\t\t4. Pending Fee");
printf("\n\t\t5. Delete Record");
printf("\n\t\t0. Exit");
printf("\n\n\tYour choice : ");
fflush(stdin);
choice = getche();
switch(choice)
{
case '1':
fseek(fp,10,SEEK_SET);
tmp = 'Y';
while((tmp == 'Y') || (tmp == 'y'))
{
printf("\n\tEnter Roll No: ");
scanf("%f", &f.r_no);
printf("\n\tEnter Name: ");
scanf(" %s", f.name);
printf("\n\tEnter Address: ");
scanf(" %s", f.add);
printf("\n\tEnter Father Name: ");
scanf(" %s", f.f_name);
printf("\n\tEnter Deposited Fee: ");
scanf("%f", &f.d_fee);
printf("\n\tEnter Stream: ");
scanf(" %s", f.stream);
fwrite(&f, size, 1, fp);
printf("\nCreate Another Student Record(Y/N)");
tmp = getche();
}
break;
case '2':
system("cls");
rewind(fp);
printf("Roll No: \tName: \tAddress: \tFather's Name: \tStream: \tDeposited Fee: \tTotal Amount: ");
while(fread(&f, size, 1, fp))
printf("\n%d \t%s \t%s \t%s \t%s \t%f \t%ld", f.r_no, f.name, f.add, f.f_name, f.stream, f.d_fee, total);
getch();
break;
case '3':
tmp='Y';
while(tmp=='Y' || tmp=='y')
{
printf("\nEnter Roll Number to Check Balance");
scanf("%d", &r_no1);
printf("\nEnter the Stream");
scanf("%s", &stream1);
rewind(fp);
flag=0;
while(fread(&f, size, 1, fp))
{
if((f.r_no==r_no1)&&(strcmp(f.stream,stream1)))
{
if(f.d_fee<=total)
{
flag=1;
printf("\nEnter amount to Deposit");
scanf("%ld", &amount);
f.d_fee = f.d_fee + amount;
fseek(fp, -size, SEEK_CUR);
fwrite(&f, size, 1, fp);
break;
}
}
}
if(flag==0)
{
printf("Sorry! Invalid Roll No.");
getch();
}
printf("Deposit More Amount!");
fflush(stdin);
tmp=getche();
}
break;
case '4':
tmp='Y';
while(tmp=='Y'||tmp=='y')
{
printf("\nEnter Roll Number to check Pending Amount");
scanf("%d", &r_no1);
printf("\nEnter the Stream");
scanf("%s", &stream1);
rewind(fp);
flag=0;
while(fread(&f, size, 1, fp))
{
if((f.r_no==r_no1)&&(strcmp(f.stream,stream1)))
{flag=1;
pending=total-f.d_fee;
printf("\nYour pending amount is: %ld", pending);
getch();
}
}
if(flag==0)
{
printf("Sorry! Invalid Roll Number");
getch();
}
fflush(stdin);
tmp=getche();
}
break;
case '5':
tmp='Y';
while(tmp=='Y'||tmp=='y')
{
printf("\nEnter Roll Number to delete");
scanf("%d",&r_no1);
ft = fopen("TEMP.txt","w");
rewind(fp);
while(fread(&f, size, 1, fp))
{
if(f.r_no!=r_no1)
fwrite(&f, 1, size, ft);
}
fclose(fp);
fclose(ft);
remove("FEES.txt");
rename("TEMP.txt", "FEES.txt");
fp=fopen("FEES.txt", "r");
printf("Delete another record(Y/N)");
fflush(stdin);
tmp = getche();
}
break;
case '0':
fclose(fp);
printf("\n\t\tProgram Terminated!!");
exit(0);
}
}}
Okay, as suggested, I used fprintf() instead of fwrite(), and now I get this force close on my program. Here's the change I made:
case '1':
tmp = 'Y';
while((tmp == 'Y') || (tmp == 'y'))
{
printf("\n\tEnter Roll No: ");
scanf("%f", &f.r_no);
printf("\n\tEnter Name: ");
scanf(" %s", f.name);
printf("\n\tEnter Address: ");
scanf(" %s", f.add);
printf("\n\tEnter Father Name: ");
scanf(" %s", f.f_name);
printf("\n\tEnter Deposited Fee: ");
scanf("%f", &f.d_fee);
printf("\n\tEnter Stream: ");
scanf(" %s", f.stream);
fprintf(fp, "%d %s %s %s %f %s \n", f.r_no, f.name, f.add, f.f_name, f.d_fee, f.stream);
printf("\nCreate Another Student Record(Y/N)");
tmp = getche();
Any help would be appreciated!
You are not writing a text file but a binary file, you can't inspect it's content with a plain text editor. You could with a HEX editor and some of them even accept defining a struct to verify the file record by record if you need to.
Or you need to write a read function that reads the binary data directly into an instance of your structure. Then print each member of the structure according to it's type.
Note that the "w" mode is for text files though, you should be using "wb" instead.
We're learning on File Processing today where we store the scores the user inputted. I got the File Processing part covered but I'm having a hard time arranging the scores in descending order. I'm thinking of using bubble sort but I don't know where to put it since we're still fairly new to the topic of File Processing. Here's my code:
#include<stdio.h>
#define MAX 100
int main(){
FILE *myPtr;
int score=0, choice;
char name[MAX]="";
while (choice != 3) {
printf("What do you want to do?\n");
printf("\t1 - Enter new score\n");
printf("\t2 - View all scores\n");
printf("Choice: ");
scanf("%d", &choice);
switch (choice){
case 1:
printf("Enter name: ");
scanf("%s", name);
printf("Enter score: ");
scanf("%d", &score);
if ((myPtr = fopen("topscores.txt", "a")) == NULL)
printf("File could not be opened. :(\n");
else {
fprintf(myPtr, "Name:\t%s", name);
fprintf(myPtr, "Score:\t%d", score);
fclose(myPtr);
printf("Score added successfully!\n");
system("pause");
}
break;
case 2:
system("cls");
printf("TOP 10 SCORES:\n\n");
if ((myPtr = fopen("topscores.txt", "r") )== NULL)
printf("File could not be opened. :(\n");
else {
printf("NAME\tSCORE\n\n");
fscanf(myPtr, "%s%d", name, &score);
while (!feof(myPtr)){
printf("%s\t%d\n", name, score);
fscanf(myPtr, "%s%d", name, &score);
}
fclose(myPtr);
printf("\n");
system("pause");
}
break;
Do I put the bubble sort in case 2 or case 1? Help, please.