Implementing bubble sort to File Processing in C - c

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.

Related

My c program keeps crashing on as it's starting

I'm making a c program for a simple library but for some reason the program keeps crashing right on startup. Like there's a menu that is displayed but it doesn't even appear it just crashes. can any one help me?
struct library
{
char name[50];
int id;
int qty;
}books[50],copy[50],delet[50],sort[50];
int i=0;
FILE *mybooks;
int main()
{
int choice; char ans;
int id;
int qty;
int s,o=0,j=0;
char name[50];
mybooks=fopen("D:\\mybooks.txt","r");
if (mybooks == NULL) printf("Error. File not found.");
else
{
while(!feof(mybooks))
{
fscanf(mybooks,"%[^\n] %d %d",books[i].name,&books[i].id,&books[i].qty);
strcpy(copy[i].name,books[i].name);
copy[i].id=books[i].id;
copy[i].qty=books[i].qty;
i++;
}
fclose(mybooks);
}
printf("Welcome to the Library.\n");
do
{
printf("Please choose an option:\n");
printf("1.Insert a book\n");
printf("2.Delete a book\n");
printf("3.Search a book by ID\n");
printf("4.Search a book by name\n");
printf("5.Display all books (sorted by name)\n");
printf("6.Display all books (unsorted)\n");
scanf("%d",&choice);
switch (choice){
case 1:
printf("You will need to enter a name, ID, and quantity of the book.\n");
printf("please enter book name:");
fflush(stdin);
fgets(name,sizeof name,stdin);
printf("please enter book ID:");
scanf("%d",&id);
printf("please enter book quantity:");
scanf("%d",&qty);
InsertBook(name,id,qty);
printf("your book has been added successfully\n");
break;
case 2:
printf("Please enter book ID:");
scanf("%d",&id);
DeleteBook(id);
printf("book successfully deleted.\n");
break;
case 3:
printf("Please enter ID of Book:");
scanf("%d",&id);
s=LinearSearch(id,j);
if (s>=0)
{
printf("Book Found.\n");
printf("Name:%s",books[s].name);
printf("ID:%d\n",books[s].id);
printf("Quantity:%d\n",books[s].qty);
}
else
printf("Sorry, the book doesn't exist.\n");
break;
case 4:
printf("Please enter name of book:");
fflush(stdin);
gets(name);
sorting();
s=BinarySearch(name,0,i);
printf("Book Found.\n");
printf("ID:%d\n",sort[s].id);
printf("Quantity:%d\n",sort[s].qty);
break;
case 5:
sorting();
while (o<i);
{
printf("%s\n",sort[o].name);
o++;
}
printf("\n");
break;
case 6:
while(o<i)
{
printf("%s",books[o].name);
o++;
}
break;
default:
printf("Invalid Choice. Please try again.\n");
break;
}
printf("do you want to choose another option?(y/n) ");
scanf(" %c",&ans);
}while(ans == 'y');
}
(I'm using functions for the library but I don't think they are causing any problem since i didn't call them yet.)
edited the question to add the structure
You have tested an end of file condition before performing any i/o on the input file. And then, when you perform the i/o with fscanf(), you did not test the result to see if the variables were successfully read.
What is happening is that scanf() is probably failing and you do not reach the end of the loop, i.e., the EOF condition. You get stuck in there until one of your assignments (strcpy(copy[i].name,books[i].name);, copy[i].id=books[i].id; or copy[i].qty=books[i].qty;) will finally cause an overflow.
To verify this, run the code in a debugger.
Using fscanf() is very tricky, always test it thoroughly.

Why my C program crash

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.

Debug assertion failed for editing and deleting records

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.

I'm unable to write the structure in a text file in C

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.

Menu not working properly

#include <stdio.h>
#include <stdlib.h> //for the clear screen function
#include <string.h>
struct customer
{
int custID;
char custName[50];
char custAddress[100];
};
typedef struct customer c;
void load_menu(void);
void customers_menu(void);
void createNew(void); //initialize your file
void add_Customer(c c1[30]); //add a new record to the file
FILE *fp;
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
do
{
printf("Customer Orders Main Menu. \n\n");
printf("Please enter your choice: \n");
printf("1. Customer's Menu \n");
printf("2. Orders Menu\n");
printf("3. Product Stock Menu\n");
printf("4. Exit\n");
printf("\n");
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: system ("cls");
customers_menu();
printf("\n");
break;
case 2: system ("cls");
orders_menu();
printf("\n");
break;
case 3: system ("cls");
stock_menu();
printf("\n");
break;
case 4: printf("Quitting program!\n");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
}
void createNew(void)
{
FILE *fp;
fp=fopen("Customer.dat", "w");
if (fp==NULL)
printf("File creation failed! \n");
else
{
printf("File created! \n");
fclose(fp);
}
}
void add_Customer (c c1[30])
{
int i, n , cc=0;
FILE *fp;
fp=fopen("Customer.dat", "a");
system("cls");
if(fp==NULL)
{
printf("File Creation Failed!");
}
system("cls");
printf("Enter the number of Customers: ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("Customer's ID (numbers only) : ");
scanf("%d", &c1[i].custID);
printf("Customer's Name : ");
gets(c1[i].custName);
printf("Customer's Address : ");
gets(c1[i].custAddress);
fwrite(&c1[i], sizeof(c), 1, fp);
}cc++;
fclose(fp);
}
void recordCount(c c1[30], int *count)
{
add_Customer(c1);
count=0;
count++;
}
void customers_menu(void)
{
int choice;
c c1[30];
int i;
do
{
printf("\n");
printf("Customers Menu \n\n");
printf("Please enter your choice: \n");
printf("1. Add Customer \n");
printf("2.\n");
printf("3.\n");
printf("4. Go back to Main Menu \n");
recordCount (c1, &i);
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1: add_Customer(c1);
createNew();
printf("\n");
break;
case 2:
printf("\n");
break;
case 3:
printf("\n");
break;
case 4: printf("Going back to Main Menu\n");
system ("cls");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
fflush(stdin);
printf("Characters are invalid, please enter a number: \n ");
choice=0;
}
}while((choice !=4));
I have a problem since when I enter the Customers Menu it is staring to execute case 1 immediately (which still doesn't work properly). Can someone help me fix this error please because I tried everything I know and it is still in vain
I think your issue is that in customers_menu() you output the menu, but do not read the selection, instead you call recordCount() which directly calls addCustomer().
After addCustomer() we return the customers_menu() which then calls scanf() for the long gone menu.
A few other notes:
gets() is not good, I suggest you use scanf() (with %s) instead.
Doing a printf() then clearing the screen is a bit pointless.
Error messages should really go to stderr (fprintf(stderr,...)) rather than stdout (printf(...))
You code is a missing trailing }.
cc is added to, but not used.
This problem coming from if (scanf("%d",&choice)==1) because scanf will not return choice. If you enter valid answer (like number), then it returns 1 and switch case work with 1. I think that's the problem.
If you enter char instead of integer, scanf will return 0.

Resources