I've written this c program to insert, view, modify and delete the records in a file. File name is emp.dat. The code for displaying, adding and deleting is working fine but the modify part is not working. The program asks to input details to modify but nothing gets updated/modified.
The Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
void main()
{
FILE *outp,*inpt;
char another,choice;
struct emp
{
int emp_no,age;
char name[40];
float bs;
};
struct emp e;
char empname[40];
long int recsize;
outp=fopen("emp.dat","r+");
if(outp=='\0')
{
outp=fopen("emp.dat","w+");
if(outp=='\0')
{
puts("cannot open file\n");
exit(1);
}
}
recsize=sizeof(e);
while(1)
{
printf("1.Add records\n");
printf("2.List records\n");
printf("3.Modify records\n");
printf("4.Delete records\n");
printf("0. exit\n");
printf("Your choice\n");
fflush(stdin);
choice=getche();
switch(choice)
{
case '1': //code to add data
.
case '2': //code to display data
case '3': //code to modify data
another='Y';
while(another=='Y')
{
printf("\nEnter name of employee to modify");
scanf("%s",empname);
rewind(outp);
while(fread(&e,recsize,1,outp)==1)
{
if(strcmp(e.name,empname)==0)
{
printf("\nenter new name,age & gs");
scanf("%d %s %d %f",&e.emp_no,&e.name,&e.age,&e.bs);
fseek(outp,-recsize,SEEK_CUR);
fwrite(&e,recsize,1,outp);
break;
}
}
printf("\nModify another record(Y/N)");
fflush(stdin);
another=getche();
}
printf("\n\n");
break;
case '4': //code to delete data
case '0':
fclose(outp);
printf("\n\n");
exit(1);
}
}
}
As can be seen in output the name doesn't change from Zaid to Cow, so does the age and gs
You really should test the return values.
The prompt asks for name,age & gs, and you enter them as asked. However scanf is instructed to get an integer (emp_no) first ("%d %s %d %f"). Missing that it fails immediately and nothing gets updated.
The situation is easily detectable: scanf returns the number of successful conversions.
Related
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.
#include<stdio.h>
int main() {
//After selling and buying i want it to modify this
struct music {
int srno;
char name[10];
int upperlimit;
int lowerlimit;
int avarn;
};
//Structure to maintain personal data
struct custormer {
int srno;
char name[5];
int upperlimit;
int lowerlimit;
int avarn;
};
FILE *f1;
int choice,amount,price;
int x,code,j=0;
struct music m1[] = {1,"Apple",100,98,10,2,"Valve",100,98,10,3,"Google",90,80,10,4,"Tesla",100,98,10};
struct music m2[10];
f1 = fopen("4.DAT","rb+");
if(f1==NULL)
{
printf("File does not exist!");
exit(0);
}
while(1)
{
printf("___________________________________\n");
printf("MENU\n");
printf("___________________________________\n");
printf("1) Stock Market\n");
printf("2) Buy\n");
printf("3) Personal Info\n");
printf("4) Sell\n");
printf("5) Exit\n");
printf("Enter choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("Stock Market\n");
printf("___________________________________\n");
for(x=0;x<4;x++)
{
printf("%d\t %s\t %d\t %d\t %d\n",m1[x].srno,m1[x].name,m1[x].upperlimit,m1[x].lowerlimit,m1[x].avarn);
fwrite(&m1,sizeof(m1),1,f1);
}
break;
}
case 2:
{
printf("Enter code of Stock:");
scanf("%d",&code);
printf("Enter number of stocks:");
scanf("%d",&amount);
printf("Enter price:");
scanf("%d",&price);
rewind(f1);
for(x=0;x<4;x++)
{
if(price>m1[x].lowerlimit&&price<m1[x].upperlimit)
{
if(m1[x].srno==code)
{
printf("Trasaction Is Succesful\n");
m1[x].avarn = m1[x].avarn-amount;
fwrite(&m1,sizeof(m1),1,f1);
m2[j].srno = j+1;
strcpy(m2[j].name,m1[x].name);
m2[j].avarn = amount;
j++;
}
}
}
break;
}
case 3:
{
for(x=0;x<j;x++)
{
printf("%d\t %s\t %d\n ",m2[x].srno,m2[x].name,m2[x].avarn);
fseek ( f1, sizeof(m1), SEEK_CUR ) ;
fwrite ( &m2, sizeof(m2), 1, f1 ) ;
}
break;
}
case 4:
{
printf("Enter code of stock to sell:");
scanf("%d", &code);
printf("Enter amount to sell:");
scanf("%d",&amount);
printf("Enter price to sell:");
scanf("%d",&price);
for(x=0;x<4;x++)
{
if(price>m1[x].lowerlimit&&price<m1[x].upperlimit)
{
if(m1[x].srno==code)
{
printf("Transaction is Sucessful\n");
m1[x].avarn = m1[x].avarn+amount;
fwrite(&m1,sizeof(m1),1,f1);
}
}
}
break;
}
case 5:
{
printf("Thanks!");
exit(0);
}
default:
{
printf("Invalid input!");
exit(0);
break;
}
}
}
fclose(f1);
return 0;
}
The program will execute and run but it will not store any data that I add when I buy or sell stocks, I'm still learning file operations, can someone correct this program or tell me how to do it? I feel like the fwrite() function is maybe not taking in the values I'm giving it The program will execute and run but it will not store any data that I add when I buy or sell stocks, I'm still learning file operations, can someone correct this program or tell me how to do it? I feel like the fwrite() function is maybe not taking in the values I'm giving it
You are using the wrong operator for testing equality.
if(f1=NULL)
This statement will assign NULL to f1, which will then evaluate to false.
You should use if (f1 == NULL) to test if it's NULL. Or just simply if (f1).
Something else strange that you are doing is opening the file twice, leaking the first handle. You should close it first, or open it only once.
Also, you should pay attention to the open mode. Your second call will actually destroy the file's contents. Read the documentation.
I have an assignment to write a program for supporting an art gallery in C. It has to be menu based program using lists. I wrote the first function of the menu and I need some help writing the other three. So I have a structure of an unique code of the painting, author's name, painting's name, price, year of the painting. I have to create a function deleting a painting using the unique code, print out all the info about every painting and modifying a painting again using said code. The data has to be in a dynamic type structure using a linked list. This is the program so far.
#include <stdio.h>
void addPainting(void);
void erasePainting(void);
void printData(void);
void modifyData(void);
int main()
{
struct paintings
{
char code[20];
char name[50];
char paintingName[50];
double price;
int year;
}painting[100];
int choice;
do
{
printf("Menu\n");
printf("To add a painting press 1.\n");
printf("To erase a painting press 2.\n");
printf("To print data for all paintings by authors alphabetically press 3.\n");
printf ("To modify data for a painting press 4.\n");
printf("To exit the program press 5.\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
addPainting();
break;
}
case 2:
{
erasePainting();
break;
}
case 3:
{
printData();
break;
}
case 4:
{
modifyData();
break;
}
default: printf ("Wrong choice. Try again\n");
break;
}
}while (choice !=5);
void addPainting()
{
FILE *fp;
struct paintings painting;
printf("Enter code:");
scanf("%s", &painting.code);
printf("Enter the name of the author:");
scanf("%s", &painting.name);
printf("Enter the name of the painting:");
scanf("%s", &painting.paintingName);
printf("Enter price:");
scanf("%lf", &painting.price);
printf("Enter the year of creation:");
scanf("%d", &painting.year);
if ((fp=fopen("paintings","wb"))==NULL)
exit(1);
if ((fwrite (&painting,sizeof(painting),1,fp)!=1))
exit(2);
fclose(fp);
}
}
First problem: You are missing the closing brace ( } ) for the main() function. (but I am sure you knew that)
The reason for the struct size error is that you are attempting to create an instance of struct painting in the void addPainting() function, when it was created with local scope in the main function, and therefore it is not visible to the function. Create struct painting with global scope if you want to use it this way:
This will build (and run) but only for the functions defined, the others are commented out. There are other problems you will have to work out, or ask about.
EDITED to fix scanf() statements, show use of fopen()/fclose(), create and write strings using sprintf()/fputs()...
void addPainting(void);
//void erasePainting(void);
//void printData(void);
//void modifyData(void);
typedef struct //created with global scope, visible to all functions
{
char code[20];
char name[50];
char paintingName[50];
double price;
int year;
}PAINTING;
PAINTING painting[100];//array of instance of PAINTING
#define PATH "C:\\play\\painting.txt" //edit to your need
int main()
{
int choice;
do
{
printf("Menu\n");
printf("To add a painting press 1.\n");
printf("To erase a painting press 2.\n");
printf("To print data for all paintings by authors alphabetically press 3.\n");
printf ("To modify data for a painting press 4.\n");
printf("To exit the program press 5.\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
addPainting();
break;
}
case 2:
{
//erasePainting();
break;
}
case 3:
{
//printData();
break;
}
case 4:
{
//modifyData();
break;
}
default: printf ("Wrong choice. Try again\n");
break;
}
}while (choice !=5);
}
void addPainting(void)
{
FILE *fp;
char stringToWrite[80];
//Note: this function could be prototyped with an int argument
// to be used as an index for the array arguments of your
// structure. Currently, the indexes are hard-coded to 0,
printf("Enter code:");
//scanf("%s", &painting[0].code);
scanf("%s", painting[0].code); //& not needed for char array (char *) et. al.
printf("Enter the name of the author:");
scanf("%s", painting[0].name);
printf("Enter the name of the painting:");
scanf("%s", painting[0].paintingName);
printf("Enter price:");
scanf("%lf", &painting[0].price);
printf("Enter the year of creation:");
scanf("%d", &painting[0].year);
fp = fopen (PATH, "a");//open for create/append text file (not write binary, "wb")
if(fp)
{
sprintf(stringToWrite, "Painting Code is: %s\n", painting[0].code);
fputs(stringToWrite, fp);
// do others same way...
//...
fclose(fp);
}
}
// I'm having issues compiling my program. Honestly, i'm a new programmer and i'm not really sure how to use certain things within my program. Can someone check my program and give me the corrections please or better thoroghly explain it ti me? It's neede for monday..//
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <time.h>
int main()
{
//File declarations//
FILE*Log;
FILE*Inventory;
FILE*Username;
char fpass_word[10]="invent";
char fusername[10]="";
//Declarations for variables//
int main;
int sub_main;
int s=0;
int s_goods;
int p_goods;
int in_goods;
int c_goods;
double Unit_price;
int item_quantity;
int invoice_num;
char pass_word1[10]=" ";
char pass_word[10]="invent";
char username[10]="inventor";
char username1[10]=" ";
char Supplier[12]=" ";
char Items_name[12]=" ";
char Invoice_date[10]=" ";
//Declarations for variables//
int u=0;
int count=0;
int option;
int choice;
int choice1;
int m=0;
int Save;
int New_inventory;
int Update_inventory;
int Print;
int Close_Program;
int t_sales;
int t_purchases;
double m_sales[4]={30000.00,50000.00,100000.00,120000.00};
}
Log=fopen("Invent.txt","w")
if(Log==NULL)
printf("File does not exist");
}
else
{
fprintf(Log,"%s",pass_word);
fclose(Log);
}
user=fopen("Username.txt","w")
if(user==NULL)
{
printf("File does not exist");
}
else
{
fprintf(user,"%s",username);
fclose(user);
}
printf("__________________________________________________________\n\n");
printf("************Please login to your account!************\n\n");
printf("__________________________________________________________\n\n");
printf("Please enter your username: \n");
scanf("%s",username);
user=fopen("Username.txt","r")
{
if(user==NULL)
{
printf("File does not exist");
}
else
{
fprintf(user,"%s",fusername);
fclose(user);
}
choice1=strncmp(username,fusername,10);
printf("Please enter password: \n");
scanf("%s",pass_word1);
Log=fopen("Invent.txt","r")
if(Log==NULL)
{
printf("File does not exist");
}
else
{
fscanf(Log,"%s",fpass_word);
fclose(Log);
}
choice=strncmp(pass_word1,fpass_word,10);
while (choice!=0 && count<3)
{
printf("*************************************************************************************\n\n");
printf("!!!!!!!!!!!!!!!!!!!!!!!!Please re-enter your login info!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
printf("*************************************************************************************\n\n");
printf(" Please enter username: \n");
scanf("%s",&username);
choice=strncmp(username,username1,10);
printf("Please enter password!\npassword:");
scanf("%s",pass_word);
choice=strncmp(pass_word,pass_word1,10);
count=count++;
//menu function!!!
getch();
system("cls");
}//login page
printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
printf("\n******************** Welcome to the INVENT BIZ main page!********************\n\n");
printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n");
printf (">>>>>>>>>>>>>>> Please select an option you desire:<<<<<<<<<<<<<<<\n\n");
printf("1: New inventory\n");
printf("2: Update inventory\n");
printf("3: Print\n");
printf("4: Save \n");
printf("5: Close Program\n");
printf("Please select an option: \n");
scanf("%d",&option);
//menu screen
while(option!=6)
{
switch(main)
{
case 1:
printf("New inventory");
Inventory=fopen("New Inventory.txt","w")
if (Inventory==NULL)
printf("This File is empty!");
}
else
{
fprintf("Please enter invoice date:\t\n");
fprintf("Please enter Supplier:\t\n");
fprintf("Please enter Item name:\t\n");
fprintf("Please enter quantity of items:\t\n");
fprintf(" Please enter invoice number:\t\n");
fprintf("Please enter Unit Price:\t\n");
}
fclose(Inventory);
// Data entered for inventory//
switch(sub-main)
{
case 10:
printf("Please enter sales for each month:%d",t_sales);
printf(" Total Sales\n");
scanf("%d",&t_sales);
break;
case 3:
printf("Print");
Inventory=fopen("New Inventory.txt","r")
fscanf(Inventory,"%d",Invoice_date);
fscanf(Inventory,"%s",Supplier);
fscanf(Inventory,"%s",Items_name);
fscanf(Inventory,"%d",&item_quantity);
fscanf(Inventory,"%d",&invoice_num);
fscanf(Inventory,"%d",&Unit_price);
fclose(Inventory);
break;
case 4:
printf("Save");
Inventory=fopen("Inventory1.txt","w");
if(Inventory==NULL)
{
printf("This file empty!!!");
}
else
{
printf("File saved");
}
fclose(Inventory);
case 5:
printf("Close Program");
exit(main);
break;
} // end switch
system("cls");
printf (">>>>>>>>>>>>>>> Please select an option you desire!!!<<<<<<<<<<<<<<<\n\n");
printf("1: New inventory\n");
printf("2: Update inventory\n");
printf("3: Print\n");
printf("4: Save \n");
printf("Please select an option: \n");
scanf("%d",&option);
}
}
system("cls");
getch();
return ();
}
You should really be more specific and not just throw down an entire program and say you want to someone to clean it up for you.
Thank being said I noticed right away you had a few improperly placed curly braces. Your very first if statement is missing an opening brace and further down you have an unnecessary opening brace after user=fopen("Username.txt", "r")
Beyond that indentation is completely off throughout and your switch statements make it really hard to follow what it is you're trying to accomplish with them.
My advice is to read through the compiler errors and locate each issue one by one, and if you're having a problem you can't solve then be specific and post the errors you're getting with your program.
#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.