Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
a- Read and print the data from the file "detyra_day.dat"
b- Add another citizen when you know the IDNR is unique
c- Change the information of a citizen without changing IDNR
d- Create a "Permit to go outside" application for only 1 person per family per day
(the applicant can apply for another family member and the applicant must be over 18 years old)
and the "Permit to go outside" is granted from 8:00 to 17:00 which lasts 2 hours.
e- Check if a citizen does have permission to go outside (print IDNR, date and time).
f- Save
g- Print all "Permissions to go outside" for all citizens and families.
h- Print the list of 10 citizens that asked for the permission the most and 10 that asked the least (exclude the ones that didn't asked at all)
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <dos.h>
#include <windows.h>
int permission;
int hour;
int minute;
int nr_people;
struct citizen{
char idnr[10];
char name[50];
char lname[50];
long int birthday;
int id_family;
};
struct birthday{
int year;
int month;
int day;
};
char fname[]={"detyra_day.dat"};
void readPeopleInfo(){
nr_people=0;
struct citizen s;
FILE *f;
f=fopen(fname,"r");
printf("\n========================================================\n\n");
printf("\t\t Details of all citizen \n\n");
printf("========================================================\n\n");
printf("IDNR\tname\tlname\tbirthday\tid_family\n\n");
if(f == NULL)
{
printf("Error opening file\n");
exit(1);
}
while(fread(&s,sizeof(struct citizen),1,f))
{
printf("%s\t",s.idnr);
printf("%s\t",s.name);
printf("%s\t",s.lname);
printf("%ld\t",s.birthday);
printf("%d\t\n\n",s.id_family);
nr_people++;
}
fclose(f);
printf("========================================================\n\n");
printf("Number of citizen = %d",nr_people);
}
void add(){
struct citizen s,s1;
int nr_people=5;
int found=0;
printf("\n Give the unique IDNR: ");
scanf("%s",&s1.idnr);
for(int i=0;i<nr_people;i++){
if(s1.idnr==s.idnr){
printf("The citizen with this IDNR exist");
found=1;
return;
}
}
if(found==0){
printf("The citizen with this IDNR doesn't 'exist");
strcpy(s.idnr,s1.idnr);
printf("\nGive the name of the citizen: ");
scanf("%s",s.name);
printf("\n Give the lname of the citizen: ");
scanf("%s",s.lname);
printf("\n Give the birthday of the citizen in the format YYYYMMDD: ");
scanf("%ld",&s.birthday);
printf("\n Give the ID of the family of the citizen: ");
scanf("%d",&s.id_family);
nr_people++;
}
}
void change(){
struct citizen s[50];
char *idnr;
printf("\n IDNR of citizen: ");
scanf("%s",&idnr);
for(int i=0;i<nr_people; i++){
if (strcmp(s[i].idnr,idnr)==0){
printf("\nGive the name of the citizen: ");
scanf("%s",s[i].name);
printf("\n Give the lname of the citizen: ");
scanf("%s",s[i].lname);
printf("\n Give the birthday of the citizen in the format YYYYMMDD: ");
scanf("%ld",&s[i].birthday);
printf("\n Give the ID of the family of the citizen: ");
scanf("%d",&s[i].id_family);
printf("\n Changed succesfully.");
return; }
printf("\n The change didn't happened.");
}
}
void permit(){
int permission;
struct birthday bday;
struct citizen s[50];
int age[nr_people];
SYSTEMTIME d;
GetLocalTime(&d);
for(int i=0;i<nr_people;i++){
if(bday.month>d.wMonth||(bday.month==d.wMonth&&bday.day>=d.wDay)){
age[i]=d.wYear-bday.year;
}
else{
age[i]=d.wYear-bday.year-1;
}
}
char *name;
char *lname;
char *chosenperson;
int id_family;
int i;
int apply=0;
int familymembers=0;
printf("Put your name: ");
scanf("%s",&name);
printf("Put your lname: ");
scanf("%s",&lname);
for (i=0;i<nr_people;i++){
if((strstr(name,s[i].name)==0&&strstr(lname,s[i].lname)==0&&age[i]>=18)){
printf("Your name is on the list and you are in the age to apply");
id_family=s[i].id_family;
apply=1;
}
}
if(apply==0){
printf("Your name is not on the list or you are not in the age to apply");
return;
}
struct citizen tmp;
for(i=0;i<nr_people;i++){
if(id_family==s[i].id_family){
tmp=s[50];
familymembers++;
}
}
for(i=0;i<familymembers;i++){
printf("%d. name: %10s",i+1,tmp.name);
}
apply=0;
printf("Give the name of the person from your family that you want to apply: ");
scanf("%s",chosenperson);
printf("\nYou chose: ");
for(i=0;i<familymembers;i++){
if(strstr(chosenperson,tmp.name)==0){
printf("%s",tmp.name);
apply=1;
}
}
if(apply==0){
printf("\nThe selected name is not on the list");
return;
}
printf("\nChose a time between 8:00 and 17:00: ");
float timez;
int hour;
int minute;
scanf("%f",&timez);
if(timez>=8.00&&timez<=17.00){
hour=timez;
minute=(timez-hour)*100;
if(minute>59){
printf("Minutes are placed wrong");
return;
}
printf("\nYour application to go out from %f to %f is accepted!",timez,timez+2);
permission=1;
}
else{
printf("You have chosen the wrong time");
return;
}
}
void control(){
permit();
struct citizen s[50];
SYSTEMTIME d;
GetLocalTime(&d);
int g=permission;
for(int i=0;i<nr_people;i++){
if(g==1){
printf("\n The citizen with IDNR: %s Date: %d/%d/%d Time: %d.%d has applied to go outside",s[nr_people].idnr,d.wYear,d.wMonth,d.wDay,hour,minute);
}
}
}
void save(){
struct citizen s[50];
FILE *f;
f=fopen("detyra_day.dat","w");
if (f==NULL){
printf("\n Error on the file");
return;
}
for(int i=0;i<nr_people; i++){
fwrite(&s[i],sizeof(struct citizen),1,f);
}
}
int main(){
char selection;
do{
printf("\n=============================");
printf("\n 1 - Read and print the data from the file detyra_day.dat");
printf("\n 2 - Add a citizen");
printf("\n 3 - Change a citizen");
printf("\n 4 - Create a Permit to go outside");
printf("\n 5 - Control the permission");
printf("\n 6 - Save");
printf("\n 7 - Print all Permissions to go outside for all citizens and families");
printf("\n 8 - Print the list of 10 citizens that asked for the permission the most and 10 that asked the least (exclude the ones that didn't asked at all)");
printf("\n 9 - Exit");
printf("\n-----------------------------");
printf("\n Zgjedhja : ");
selection=getch();
switch(selection){
case '1':
readPeopleInfo();
break;
case '2':
add();
break;
case '3':
change();
break;
case '4':
permit();
break;
case '5':
control();
break;
case '6':
save();
break;
case '9':
exit(0);
}
getch();
} while(selection!='9');
return 0;
}
After I press Run and try number 1 which is read and print it prints every person as 1 not as the struct says. For example I want to print it like this:
IDNR: H65328040Q
Name: Azbie
Lname: Gockaj
Birthday (YYYYMMDD format):19760328
ID_Family: 1
Instead I get:
INDR: Name: Lname: Birthday: ID_Family:
and then every person ordered
This is the detyra_day.dat file
H65328040Q Azbie Gockaj 19760328 1
J70507042S Ledion Celaj 19970507 1
G70312202S Pellumb Osmani 19670312 2
H45827189P Albina Osmani 19740827 2
There are a number of errors.
First, you need a global array of struct citizen instead of having a function scoped struct citizen in each function.
In struct citizen, idNr was too small to contain a 10 digit ID number. It has to be [at least] one more to account for the EOS char at the end of the string.
Using fread and fwrite to access the data file. They are for binary files, but you have a text file. You need to use fscanf and fprintf respectively.
Using (e.g.) a [function scoped] char *name;. This is a pointer to a char [array/string] and it is uninitialized. Change this to char name[100];
Using strstr instead of strcmp.
Use of scanf or fscanf was inconsistent. If you had compiled with -Wall -Wextra to enable warnings [gcc], they would have become apparent.
It's bad practice to intermix getch [fgetc] and scanf on the same stream.
For consistency, I've added a prompt function instead of the various printf(...); scanf(...); sequences for prompting the user.
You didn't really use your struct birthday in the code.
Here's the cleaned up code. Some basics have been tested, but there are still some issues I couldn't get to. In most places, I've used #if 0 to denote your old code [vs. my new code]
#include <stdio.h>
#include <string.h>
#ifndef __linux__
#include <conio.h>
#include <dos.h>
#endif
#include <windows.h>
#ifdef __linux__
#include <time.h>
int
getch(void)
{
char buf[1000];
int chr;
if (fgets(buf,sizeof(buf),stdin) != 0)
chr = buf[0];
else
chr = -1;
return chr;
}
WINBASEAPI VOID WINAPI
GetLocalTime(LPSYSTEMTIME lps)
{
time_t tod;
struct tm *tm;
tod = time(NULL);
tm = localtime(&tod);
lps->wYear = tm->tm_year + 1900;
lps->wMonth = tm->tm_mon + 1;
lps->wDayOfWeek = tm->tm_wday;
lps->wDay = tm->tm_mday;
lps->wHour = tm->tm_hour;
lps->wMinute = tm->tm_min;
lps->wSecond = tm->tm_sec;
lps->wMilliseconds = 0;
}
#endif
int permission;
int hour;
int minute;
int nr_people;
struct birthday {
int year;
int month;
int day;
};
struct citizen {
#if 0
char idnr[10];
#else
char idnr[10 + 1];
#endif
char name[50];
char lname[50];
struct birthday birthday;
int id_family;
};
#define CITMAX 50
struct citizen citlist[CITMAX];
char fname[] = { "detyra_day.dat" };
void
prompt(const char *str,char *buf)
{
printf("%s: ",str);
fflush(stdout);
fgets(buf,100,stdin);
char *cp = strchr(buf,'\n');
if (cp != NULL)
*cp = 0;
}
void
getbday(const char *buf,struct birthday *bday)
{
sscanf(buf,"%4d%2d%2d",&bday->year,&bday->month,&bday->day);
}
void
loadPeopleInfo()
{
struct citizen *s;
char birthday[100];
FILE *f;
nr_people = 0;
f = fopen(fname, "r");
if (f == NULL) {
printf("Error opening file\n");
exit(1);
}
while (1) {
s = &citlist[nr_people];
if (fscanf(f," %s %s %s %s %d\n",
s->idnr,s->name,s->lname,birthday,&s->id_family) != 5)
break;
getbday(birthday,&s->birthday);
nr_people++;
if (nr_people >= CITMAX)
break;
}
fclose(f);
}
void
printPeopleInfo()
{
struct citizen *s;
printf("\n========================================================\n\n");
printf("\t\t Details of all citizen \n\n");
printf("========================================================\n\n");
printf("IDNR\t\tname\tlname\tbirthday\tid_family\n\n");
for (int i = 0; i < nr_people; ++i) {
s = &citlist[i];
printf("%s\t", s->idnr);
printf("%s\t", s->name);
printf("%s\t", s->lname);
struct birthday *bday = &s->birthday;
printf("%4.4d%2.2d%2.2d\t",bday->year,bday->month,bday->day);
printf("%d\t\n", s->id_family);
}
printf("========================================================\n\n");
printf("Number of citizen = %d\n", nr_people);
}
void
add()
{
#if 0
struct citizen s, s1;
#else
struct citizen *s;
struct citizen s1;
#endif
#if 0
int nr_people = 5;
#endif
int found = 0;
char buf[100];
#if 0
printf("\n Give the unique IDNR: ");
scanf("%s\n", &s1.idnr);
#else
prompt("Give the unique IDNR",s1.idnr);
#endif
for (int i = 0; i < nr_people; i++) {
s = &citlist[i];
#if 0
if (s1.idnr == s->idnr) {
#else
if (strcmp(s1.idnr,s->idnr) == 0) {
printf("The citizen with this IDNR exist\n");
found = 1;
return;
}
#endif
}
if (found == 0) {
s = &citlist[nr_people];
printf("The citizen with this IDNR doesn't 'exist\n");
strcpy(s->idnr, s1.idnr);
#if 0
printf("\nGive the name of the citizen: ");
scanf("%s\n", s->name);
#else
prompt("Give the name of the citizen",s->name);
#endif
#if 0
printf("\n Give the lname of the citizen: ");
scanf("%s\n", s->lname);
#else
prompt("Give the lname of the citizen",s->lname);
#endif
#if 0
printf("\n Give the birthday of the citizen in the format YYYYMMDD: ");
scanf("%s\n",buf);
#else
prompt("Give the birthday of the citizen in the format YYYYMMDD",buf);
#endif
getbday(buf,&s->birthday);
#if 0
printf("\n Give the ID of the family of the citizen: ");
scanf("%d\n", &s->id_family);
#else
prompt("Give the ID of the family of the citizen",buf);
sscanf(buf,"%d", &s->id_family);
#endif
nr_people++;
}
}
void
change()
{
struct citizen *s;
char birthday[100];
#if 0
char *idnr;
#else
char idnr[100];
#endif
printf("\n IDNR of citizen: ");
#if 0
scanf("%s", &idnr);
#else
scanf("%s\n",idnr);
#endif
for (int i = 0; i < nr_people; i++) {
s = &citlist[i];
if (strcmp(s->idnr, idnr) == 0) {
printf("\nGive the name of the citizen: ");
scanf("%s\n", s->name);
printf("\n Give the lname of the citizen: ");
scanf("%s\n", s->lname);
printf("\n Give the birthday of the citizen in the format YYYYMMDD: ");
scanf("%s\n", birthday);
getbday(birthday,&s->birthday);
printf("\n Give the ID of the family of the citizen: ");
scanf("%d\n", &s->id_family);
printf("\n Changed succesfully.");
return;
}
#if 0
printf("\n The change didn't happened.");
#endif
}
#if 1
printf("\n The change didn't happened.");
#endif
}
void
permit()
{
#if 0
struct birthday bday;
#else
struct birthday *bday;
#endif
struct citizen *s;
int age[nr_people];
SYSTEMTIME d;
GetLocalTime(&d);
for (int i = 0; i < nr_people; i++) {
s = &citlist[i];
bday = &s->birthday;
if (bday->month > d.wMonth ||
(bday->month == d.wMonth && bday->day >= d.wDay)) {
age[i] = d.wYear - bday->year;
}
else {
age[i] = d.wYear - bday->year - 1;
}
}
#if 0
char *name;
char *lname;
char *chosenperson;
#else
char name[100];
char lname[100];
char chosenperson[100];
#endif
int id_family;
int i;
int apply = 0;
int familymembers = 0;
#if 0
printf("Put your name: ");
scanf("%s", &name);
#else
prompt("Put your name",name);
#endif
#if 0
printf("Put your lname: ");
scanf("%s", &lname);
#else
prompt("Put your lname",lname);
#endif
// NOTE/BUG: use strcmp instead of strstr
for (i = 0; i < nr_people; i++) {
s = &citlist[i];
if ((strcmp(name, s->name) == 0 && strcmp(lname, s->lname) == 0 &&
age[i] >= 18)) {
printf("Your name is on the list and you are in the age to apply [%d]\n",age[i]);
id_family = s->id_family;
apply = 1;
}
}
if (apply == 0) {
printf("Your name is not on the list or you are not in the age to apply");
return;
}
struct citizen tmp[nr_people];
for (i = 0; i < nr_people; i++) {
s = &citlist[i];
if (id_family == s->id_family) {
tmp[familymembers++] = *s;
}
}
for (i = 0; i < familymembers; i++) {
printf("%d. name: %10s\n", i + 1, tmp[i].name);
}
apply = 0;
prompt("Give the name of the person from your family that you want to apply ",chosenperson);
printf("\nYou chose: ");
for (i = 0; i < familymembers; i++) {
if (strcmp(chosenperson, tmp[i].name) == 0) {
printf("%s", tmp[i].name);
apply = 1;
}
}
if (apply == 0) {
printf("\nThe selected name is not on the list");
return;
}
printf("\nChose a time between 8:00 and 17:00: ");
float timez;
int hour;
int minute;
scanf("%f", &timez);
if (timez >= 8.00 && timez <= 17.00) {
hour = timez;
minute = (timez - hour) * 100;
if (minute > 59) {
printf("Minutes are placed wrong");
return;
}
printf("\nYour application to go out from %f to %f is accepted!",
timez, timez + 2);
permission = 1;
}
else {
printf("You have chosen the wrong time");
return;
}
}
void
control()
{
permit();
SYSTEMTIME d;
struct citizen *s;
GetLocalTime(&d);
int g = permission;
for (int i = 0; i < nr_people; i++) {
s = &citlist[i];
if (g == 1) {
printf("\n The citizen with IDNR: %s Date: %d/%d/%d Time: %d.%d has applied to go outside",
s->idnr, d.wYear, d.wMonth, d.wDay, hour, minute);
}
}
}
void
save()
{
struct citizen *s;
struct birthday *bday;
FILE *f;
f = fopen("detyra_day.dat", "w");
if (f == NULL) {
printf("\n Error on the file");
return;
}
for (int i = 0; i < nr_people; i++) {
s = &citlist[i];
fprintf(f,"%s ", s->idnr);
fprintf(f,"%s ", s->name);
fprintf(f,"%s ", s->lname);
bday = &s->birthday;
fprintf(f,"%4.4d%2.2d%2.2d ",bday->year,bday->month,bday->day);
fprintf(f,"%d\n", s->id_family);
}
#if 1
fclose(f);
#endif
}
int
main()
{
char buf[100];
int selection = 0;
loadPeopleInfo();
do {
printf("\n=============================");
printf("\n 1 - Read and print the data from the file detyra_day.dat");
printf("\n 2 - Add a citizen");
printf("\n 3 - Change a citizen");
printf("\n 4 - Create a Permit to go outside");
printf("\n 5 - Control the permission");
printf("\n 6 - Save");
printf("\n 7 - Print all Permissions to go outside for all citizens and families");
printf("\n 8 - Print the list of 10 citizens that asked for the permission the most and 10 that asked the least (exclude the ones that didn't asked at all)");
printf("\n 9 - Exit");
printf("\n-----------------------------\n");
prompt("Zgjedhja",buf);
selection = buf[0];
switch (selection) {
case '1':
printPeopleInfo();
break;
case '2':
add();
break;
case '3':
change();
break;
case '4':
permit();
break;
case '5':
control();
break;
case '6':
save();
break;
#if 0
case '9':
exit(0);
#endif
}
#if 0
getch();
#endif
} while (selection != '9');
return 0;
}
I made a C program to keep track of the distanced traveled by buses and hours worked by employees, both have ID as the primary key, these save on 2 different files. The code compiles but does not show anything, care to help? I used different sources for help with this code but I don't think that's the problem since a similar code runs well
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 100
int provbid;
int proveid;
int login();
void menu2();
void menu3();
void bus_mgm();
void emp_mgm();
typedef struct bus_data
{
int busid;
float distrav;
}bus;
typedef struct emp_data
{
int empid;
float hrswrkd;
}emp;
void addb(int*,bus[]);
void adde(int*,emp[]);
void viewb(int*,bus[]);
void viewe(int*,emp[]);
void updateb(int*,bus[]);
void updatee(int*,emp[]);
void deleteb(int*,bus[]);
void deletee(int*,emp[]);
int searchb(int,bus[]);
int searche(int,emp[]);
void readfileb(int*,bus[]);
void readfile(int*,emp[]);
void writefileb(int,bus[]);
void writefilee(int,emp[]);
int main(){
int el = 0;
emp eplist[SIZE];
readfile(&el, eplist);
int option1;
int p = 0;
p = login();
if (p==1){
printf("\nWelcome to 'Company Manager' user\n");
}
system("pause");
system("cls");
printf("Please slect an option:\n");
printf("1 for bus managment menu\n");
printf("2 For employee managment menu\n");
scanf("%d", &option1);
while (option1 != 3){
switch(option1){
case 1:
menu2();
break;
case 2:
menu3();
break;
default:
{
if (option1 != 3){
printf("/n Option is not supported.");
}
}
}
system("pause");
}
return 0;
}
int login(){
int pwd = 12345678;
int count = 0;
int pw;
while (count != 5){
printf("Please enetr password. \n");
scanf("%d",&pw);
if (pw == pwd){
printf("Password accepted");
return 1;
}
else{
printf("\n Wrong Password, try again.\n");
}
count++;
printf("You have done %d chances out of 5\n", count);
}
return 0;
}
void menu2(){
int choice;
int bl = 0;
bus bslist[SIZE];
readfileb(&bl, bslist);
printf("Welcome to the bus menu.\n");
printf("Please select an option:\n1: Add bus information\n2: View bus information\n 3: Update bus information\n 4: Delete bus information\n 5: Return to login menu\n ");
scanf("&d",choice);
switch (choice){
case 1:
addb(&bl, bslist);
case 2:
viewb(&bl, bslist);
case 3:
updateb(&bl, bslist);
case 4:
deleteb(&bl, bslist);
case 5:
main();
default:
printf("you have not selected a proper option");
}
}
void menu3(){
int choice;
int el = 0;
emp eplist [SIZE];
readfile(&el, eplist);
printf("Welcome to the Employee menu menu.\n");
printf("Please select an option:\n1: Add Employee information\n2: View Employee information\n 3: Update Employee information\n 4: Delete Employee information\n 5: Return to login menu ");
scanf("&d", choice);
switch (choice){
case 1:
adde(&el, eplist);
case 2:
viewe(&el, eplist);
case 3:
updatee(&el, eplist);
case 4:
deletee(&el, eplist);
case 5:
main();
default:
printf("you have not selected a proper option");
}
}
void addb(int *loc ,bus list[]){
printf("Add bus information");
int n = searchb( *loc, list);
if (n != -1){
printf("This ID is already being used.");
}
else
{
list[*loc].busid = provbid;
fflush(stdin);
printf("Please enter the total distance traveled, the number you have given will be accepted as km: ");
scanf("%f", &list[*loc].distrav);
*loc = *loc + 1;
}
}
void adde(int*loc ,emp list[]){
printf("Add Employee information");
int n = searche( *loc, list);
if (n != -1){
printf("This ID is already being used.");
}
else
{
list[*loc].empid = proveid;
fflush(stdin);
printf("Please enter the total hours worked: ");
scanf("%f", &list[*loc].hrswrkd);
*loc = *loc + 1;
}
}
void viewb(int *loc ,bus list[]){
int meh;
printf("Showing information of all buses.\n");
for(meh = 0; meh < *loc; meh++)
{
printf("Bus ID is: %d\n", list[meh].busid);
printf("Distance traveled is: %.1f\n", list[meh].distrav);
}
}
void viewe(int *loc,emp list[]){
int meh;
printf("Showing information of all Employess.\n");
for(meh = 0; meh < *loc; meh++)
{
printf("Employee ID is: %d\n", list[meh].empid);
printf("Hours worked are: %.1f\n", list[meh].hrswrkd);
}
}
void updateb(int *loc,bus list[]){
int tempbid;
printf("Update bus information");
tempbid = searchb(*loc, list);
if( tempbid== -1)
{
printf("This ID does not exist.\n");
}
else
{
printf("Enter new distanced traveled: ");
scanf("%f", &list[tempbid].distrav);
printf("Distance traveled has been updated. \a");
}
}
void updatee(int *loc ,emp list[]){
int tempeid;
printf("Update employee information");
tempeid = searche(*loc, list);
if( tempeid== -1)
{
printf("This ID does not exist.\n");
}
else
{
printf("Enter new hours worked: ");
scanf("%f", &list[tempeid].hrswrkd);
printf("Hours worked has been updated. \a");
}
}
void deleteb(int *loc, bus list[]){
int tempbid, meh;
printf("Delete bus info");
tempbid = searchb(*loc, list);
if(tempbid == -1)
{
printf("This ID does not exist.\n");
}
else
{
for(meh = tempbid; meh < *loc; meh++)
{
list[meh].busid = list[meh + 1].busid;
list[meh].distrav = list[meh + 1].distrav;
}
*loc = *loc - 1;
printf("Bus ID %d has been deleted.\n", tempbid);
}
}
void deletee(int *loc,emp list[]){
int tempeid, meh;
printf("Delete employee info");
tempeid = searche(*loc, list);
if(tempeid == -1)
{
printf("This ID does not exist.\n");
}
else
{
for(meh = tempeid; meh < *loc; meh++)
{
list[meh].empid = list[meh + 1].empid;
list[meh].hrswrkd = list[meh + 1].hrswrkd;
}
*loc = *loc - 1;
printf("Employee ID %d has been deleted.\n", tempeid);
}
}
int searchb(int loc, bus list[]){
int meh;
printf("Enter bus ID: ");
scanf("&d", provbid);
for(meh=0; meh<loc; meh++){
if(list[meh].busid == provbid)
return meh;
}
return -1;
}
int searche(int loc ,emp list[]){
int meh;
printf("Enter employee ID: ");
scanf("&d", proveid);
for(meh=0; meh<loc; meh++){
if(list[meh].empid == proveid)
return meh;
}
return -1;
}
void readfileb(int *loc, bus list[]){
FILE *bd;
bd = fopen("Bus Data.txt", "r");
if(bd != NULL)
{
while(!feof(bd))
{
fscanf(bd, "%d %f ", &list[*loc].busid, &list[*loc].distrav);
*loc = *loc + 1;
}
}
fclose(bd);
}
void readfile(int *loc, emp list[]){
FILE *ed;
ed = fopen("Employee Data.txt", "r");
if(loc != NULL)
{
while(!feof(ed))
{
fscanf(ed, "%d %f ", &list[*loc].empid, &list[*loc].hrswrkd);
*loc = *loc + 1;
}
}
fclose(ed);
}
Thank you for all your help, the first problem was with scanf which I did not see so thank you for pointing it out and the other is the first 3 lines of main, the int el = 0; emp eplist[SIZE];and readfile(&el, eplist); were not supposed to be in this function.
I am working on a dog database and have one bug I cannot figure out.
The bug is: Thread 1: signal SIGABRT.
Every time I try to search or change for a dog, I get this error code.
My code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SZ_NAME 32
#define SZ_BREED 32
#define SZ_COLOR 16
#define SZ_SEX 8
struct dog_entry
{
char name [SZ_NAME];
char breed [SZ_BREED];
char color [SZ_COLOR];
float weight;
int age;
char sex [SZ_SEX];
};
#define REC_SIZE sizeof(struct dog_entry)
struct dog_entry record[REC_SIZE];
char pr_menu(void);
void addRecord(struct dog_entry *reg, int type);
void modifyRecord(int);
void delete_dog(int g, struct dog_entry *rec);
void view_dog(int, struct dog_entry *reg);
int find_dog(int, struct dog_entry *rec);
void searchRecord(int, struct dog_entry *rec);
int main()
{
struct dog_entry reg;
int i = 0, n;
while(free)
{
char ch = pr_menu();
switch(ch)
{
case '1':
addRecord(®, 1);
i++;
break;
case '2':
addRecord(®, 2);
break;
case '3': delete_dog(1, ®);
break;
case '4': view_dog(1, ®);
break;
case '5': searchRecord(n, ®);
break;
default: break;
}
if (ch == '6') // exit
break;
}
// system("pause");
}
char pr_menu(void)
{
char ch;
// system("cls");
printf("\n Menu:\n 1.Add\n 2.Change\n 3.Delete\n 4.View\n 5.Search\n 6.Exit\n \nEnter Choice: ");
scanf("%c", &ch);
return ch;
}
//Function that adds a record
void addRecord(struct dog_entry *rec, int type)
{
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "w+");//definition of file
// system("cls");
printf("Add the Dog: ");
printf("\n Enter Name: ");
scanf("%s", rec->name);
printf("\n Enter Breed: ");
scanf("%s", rec->breed);
printf("\n Enter Color: ");
scanf("%s", rec->color);
printf("\n Enter Weight: ");
scanf("%f", &rec->weight);
printf("\n Enter Age: ");
scanf("%d", &rec->age);
printf("\n Enter Sex: ");
scanf("%s", rec->sex);
fseek(f, 0, SEEK_END);
fwrite(&rec, sizeof(struct dog_entry), 1, f);//save the data
fclose(f);//close the file
printf("\n\n");
// system("pause");
}
//Function that modifies the record
void modifyRecord(int index)
{
}
//Function that displays records
void view_dog(int total, struct dog_entry *rec)
{
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "r+");//definition of file
char name [SZ_NAME];
// system("cls");
printf("View the Dog: ");
printf("\n Enter Dog's Name: ");
scanf("%s", name);
rewind(f);
while(fread(&rec, sizeof(struct dog_entry), 1, f))
{ //apertura del while
if(strcmp(name, rec->name) == 0)//compara una cadena de caracteres
{
printf("\n Name: %s", rec->name);
printf("\n Breed: %s", rec->breed);
printf("\n Color: %s", rec->color);
printf("\n Weight: %f", rec->weight);
printf("\n Age: %d", rec->age);
printf("\n Sex: %s", rec->sex);
printf("\n\n");
// system("pause");
break;
}
}
fclose(f);//close the file
}
int find_dog(int g, struct dog_entry *rec){
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "r+");//definition of file
char name [SZ_NAME];
printf("\n Enter Dog's Name: ");
scanf("%s", name);
rewind(f);
int c;
while(fread(&rec, sizeof(struct dog_entry), 1, f))
{ //apertura del while
if(strcmp(name, rec->name) == 0)//compara una cadena de caracteres
{
c++;
break;
}
}
fclose(f);//close the file
return c;
}
void delete_dog(int g, struct dog_entry *rec){
FILE * f;//define donde se guarda el archivo
f = fopen("database_dog.txt", "r+");//definition of file
char name [SZ_NAME];
int num = 0;
// system("cls");
printf("Delete Record: ");
printf("\n Enter Dog's number: ");
scanf("%d", &num);
fseek(f, num * sizeof(struct dog_entry), SEEK_SET);
fread(&rec, sizeof(struct dog_entry), 1, f);
fclose(f);//close the file
}
//Function that searches for the record
void searchRecord(int n, struct dog_entry *rec)
{
char dog[SZ_NAME];
int j;
int flag = 0;
flag = find_dog(0, rec);
if(flag == 1)
printf("Record exists\n");
else
printf("No such record exists\n");
}
In find_dog() on line 161:
fread(&rec, sizeof(struct dog_entry), 1, f);
rec is already a pointer, so you shouldn't take its address.
You've got the same problem in view_dog() on line 126.
I found this out by running a program called Valgrind, which you should definitely get and learn how to use if you are a C programmer.
I try to make a program about student registration.
This is my header file:
#ifndef STUDENTREGISTRATION_H_
#define STUDENTREGISTRATION_H_
typedef struct {
char name[30];
char surname[30];
char faculty[30];
char department[30];
int age;
int grade;
int count;
} STUDENT_STRUCT, *STUDENT;
STUDENT_STRUCT students[100];
STUDENT_STRUCT empty;
void *data_init();
void *data_set(STUDENT s);
void addStudent(int count,STUDENT s);
void displayList(int count);
void free_list(STUDENT s);
void deleteStudent(int index,int count);
void Choice();
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "StudentREGISTRATION.h"
void *data_set(STUDENT s) {
s = students;
return s;
}
void addStudent(int count,STUDENT s) {
printf("Please enter an information about student:\n");
printf("Name:");
scanf("%s", s->name);
printf("Surname:");
scanf("%s", s->surname);
printf("Faculty:");
scanf("%s", s->faculty);
printf("Department:");
scanf("%s", s->department);
printf("Age:");
scanf("%d", &s->age);
printf("Grade:");
scanf("%d", &s->grade);
students[count].age = s->age;
students[count].grade=s->grade;
strcpy(students[count].department,s->department);
strcpy(students[count].faculty,s->faculty);
strcpy(students[count].name,s->name);
strcpy(students[count].surname, s->surname);
free_list(s);
}
void displayList(int count) {
int i;
for (i = 0; i < count; i++) {
if(students[i].name[0] != "\0" && students[i].surname[0] != "\0" && students[i].faculty[0] != "\0" && students[i].department[0] !="\0"&&students[i].age != 0 && students[i].grade != 0)
{
printf("%d.) %s %s %s %s %d %d \n", i + 1, students[i].name,
students[i].surname, students[i].faculty,
students[i].department, students[i].grade, students[i].age);
}
}
}
void free_list(STUDENT s) {
free(s);
}
void deleteStudent(int index,int count) {
int i;
for(i=0;i<count;i++)
{
if(index-1==i)
{
students[i].name[0]="\0";
students[i].surname[0]="\0";
students[i].department[0]="\0";
students[i].faculty[0]="\0";
students[i].age=0;
students[i].grade=0;
}
}
displayList(count);
}
void *data_init()
{
STUDENT s=(STUDENT)malloc(sizeof(STUDENT_STRUCT));
return s;
}
void Choice() {
STUDENT s;
int a=0;
printf("Enter your choice to do with a program\n");
printf("Press A for adding student\n");
printf("Press L to display a student list\n");
printf("Press D for deleting student\n");
printf("Press E for exit\n");
char choice = ' ';
int index;
while (choice != 'E') {
printf("Your choice:");
scanf("%c", &choice);
switch (choice) {
case 'A':
s=data_init(s);
addStudent(a,s);
a++;
break;
case 'L':
displayList(a);
break;
case 'D':
printf("Enter an index:");
scanf("%d ",index);
deleteStudent(index,a);
break;
}
}
exit(1);
}
I got segmentation fault(code dump) error, when program try to run delete function in switch case. Where is my fault in this code, i guess its all about pointer. But i try to allocate and deallocate for each member of students. Where is the problem, if there is someone to tell me, i'll appreciate. Thanks.
I'd first try checking that the index is between 0 and count before doing anything else. That could be causing the error right there. Also, you don't seem to close the #ifndef in the header file with #endif.
Also as someone pointed out, scanf should give an address instead of a variable. ex:
scanf("%d ", &z);
I'm having a minor issue with my Address book, if I attempt to load the contact data without having entered and saving at least a single contact info, the program returns a "0" and freezes. Also, I feel that i need to add a remove contact function in this program as well, if anyone would help me out with that it'd be very much appreciated =D.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define NAME 40
#define LNAME 40
#define ADDRESS 100
#define PCODE 6
#define PNUM 10
#define MAX 10
void Insert();
void Display();
void Search();
void Save();
void Load();
void Exit();
char temp [10];
typedef struct contact //defines the structure for our address book
{
char name [NAME ];
char Lname [LNAME ];
char address[ADDRESS];
char Pcode [PCODE];
char Pnum [PNUM];
}
contact;
int counter = 0;
int placeHolder = 0;
int loadContact;
int fileCount;
int save = 0;
FILE *PFileOut;
contact arrayContact [MAX];
int main()
{
int option;
char filechar;
do
{
printf("\n***Personal Contact Book V1.0***\n\n");
printf("1.Add new contact\n");
printf("2.Display current contacts\n");
printf("3.Search for a contact\n");
printf("4.Save contacts to file\n");
printf("5.Load contacts to file\n");
printf("6.Exit\n\n");
printf("> ");
scanf("%d", &option);
switch (option)
{
case 1:
Insert();
break;
case 2:
Display();
break;
case 3:
Search();
break;
case 4:
Save();
break;
case 5:
Load();
break;
case 6:
Exit();
break;
default:
printf("That is not a valid input, please choose between (1-6)");
}
}
while(option !=6 );
}
void Insert()
{
char option;
if(placeHolder>=10){
printf("Your contact list is full!");
return;
}
do{
printf("Contact Number: %d\n", counter+1);
printf("First name: ");
scanf(" %[^\n]s", arrayContact[counter].name);
printf("Last name: ");
scanf(" %[^\n]s", arrayContact[counter].Lname);
printf("Address: ");
scanf(" %[^\n]s", arrayContact[counter].address);
printf("Postal Code: ");
scanf(" %[^\n]s", arrayContact[counter].Pcode);
printf("Phone: ");
scanf(" %[^\n]s", arrayContact[counter].Pnum);
placeHolder++;
counter++;
printf("Press y/Y if you wish to add another contact, any key to return to main menu\n");
scanf(" %c",&option);
printf("\n");
}while( (option =='y'|| option == 'Y')&& placeHolder<MAX);
}
void Display()
{
counter = 0;
while(counter<placeHolder){
printf("Contact Number: %d\nFirst Name: %s\nLast Name: %s\nAddress: %s\nPostal Code: %s\nPhone: %s\n\n",counter+1,arrayContact[counter].name,
arrayContact[counter].Lname,arrayContact[counter].address,arrayContact[counter].Pcode,arrayContact[counter].Pnum);
counter++;
}
counter = placeHolder;
}
void Search()
{
char search [40];
char compare [40];
int counterLetter;
int counterContact;
int verify = 0;
printf("What is the contact's Last name? ");
scanf(" %s", search);
for( counterLetter = 0; search[ counterLetter ] != '\0'; counterLetter++ ) {
search[ counterLetter ] = tolower( search[ counterLetter ] );
}
for( counterContact = 0; counterContact<placeHolder ; counterContact++ ){
strcpy(compare,arrayContact[counterContact].Lname);
for( counterLetter = 0; compare[ counterLetter ] != '\0'; counterLetter++ ) {
compare[ counterLetter ] = tolower( compare[ counterLetter ] );
}
if( strcmp( search, compare ) == 0 ){
printf("Contact Number: %d\nFirst Name: %s\nLast Name: %s\nAddress: %s\nPostal Code: %s\nPhone: %s\n\n",counterContact+1,
arrayContact[counterContact].name,arrayContact[counterContact].Lname,arrayContact[counterContact].address,arrayContact[counterContact].Pcode,
arrayContact[counterContact].Pnum);
verify = 1;
}
}
if(verify == 0){
printf("No results found");
}
}
void Save()
{
PFileOut = fopen("Contact Book.dat","w");
fprintf(PFileOut,"%d\n",placeHolder);
for(counter = 0;counter<placeHolder;counter++){
fprintf(PFileOut,"\n%s\n%s\n%s\n%s\n%s",arrayContact[counter].name,arrayContact[counter].Lname,arrayContact[counter].address,arrayContact[counter].Pcode,
arrayContact[counter].Pnum);
}
fclose(PFileOut);
save = 1;
printf("\nSuccessfully Saved!!\n");
}
void Load()
{
char temp[40];
PFileOut = fopen("Contact Book.dat","r");
fscanf(PFileOut, "%d", &fileCount);
printf("%d\n", fileCount);
while(!feof(PFileOut)){
fscanf(PFileOut,"%s",&arrayContact[placeHolder].name);
fscanf(PFileOut,"%s",&arrayContact[placeHolder].Lname);
fscanf(PFileOut," %[^\n]s",&arrayContact[placeHolder].address);
fscanf(PFileOut,"%s",&arrayContact[placeHolder].Pcode);
fscanf(PFileOut, " %[^\n]s",&arrayContact[placeHolder].Pnum);
placeHolder++;
}
fclose(PFileOut);
}
void Exit()
{ char option6;
while(save!=1){
printf("It seems you have not saved your progress. Would you like to save? (y/n)");
scanf(" %c", &option6);
if(option6 == 'y'|| option6 == 'Y')
{
Save();
}
else
{
puts ("\nThank you for using Contact Book");
exit(0);
}
}
puts ("\nThank you for using Contact Book");
exit(0);
}
You have lots of problems with your program.
If the .dat file does not exist, then the fopen will fail, leaving the file pointer as NULL.
The subsequent fscanf will also not work, which is why you get 0 for the record count. The behaviour of feof with a NULL file pointer is undefined, so that's probably where you are hanging. By all rights, this program should crash.