My code is as follows:
#define MAX_ELEMENTS 100
#define MAXIMUM_LENGTH 50
typedef struct {
char teacher;
int id;
char day[MAXIMUM_LENGTH];
char startingTime[MAXIMUM_LENGTH];
char endingTime[MAXIMUM_LENGTH];
} officehours;
officehours list[MAX_ELEMENTS];
int c = 0;
char filenamep[20];
void store_office_hour(char teacher, officehours data[], int count, char* filename) {
FILE* fp = fopen(filename, "w");
if (fp == NULL) {
printf("ERROR in %s: Unable to open file.n", __func__);
return;
}
for (int i = 0; i < count; i++) {
fprintf(fp, "%d %s %s %sn", data[i].id, data[i].day, data[i].startingTime, data[i].endingTime);
fprintf(stderr, "DEBUG: %d %s %s %s n", data[i].id, data[i].day, data[i].startingTime, data[i].endingTime);
}
fclose(fp);
}
void insert_office_hour(char teacher) {
filenamep[0] = teacher;
filenamep[1] = '';
strcat(filenamep, ".txt");
FILE* fp = fopen(filenamep, "r");
if (fp != NULL) {
c = 0;
while (fscanf(fp, "%d %s %s %s", &list[c].id, list[c].day, list[c].startingTime, list[c].endingTime) == 4) {
c++;
}
fclose(fp);
}
if (c >= MAX_ELEMENTS) {
printf("ERROR in %s: Database is full.n", __func__);
return;
}
officehours input;
getchar();
printf("ttEnter identification number: ");
scanf("%d", &input.id);
getchar();
printf("ttEnter a day: ");
read_line(input.day, MAXIMUM_LENGTH);
printf("ttEnter starting hour: ");
read_line(input.startingTime, MAXIMUM_LENGTH);
printf("ttEnter ending hour: ");
read_line(input.endingTime, MAXIMUM_LENGTH);
if (find_office_hour(list, c, input.id) != -1) {
printf("This office hour already exists.n");
return;
}
list[c++] = input;
store_office_hour(teacher, list, c, filenamep);
}
int read_line(char str[], int n) {
int ch, i = 0;
while (isspace(ch = getchar()));
while (ch != 'n') {
if (i < n - 1)
str[i++] = ch;
ch = getchar();
}
str[i] = '';
return i;
}
When inserting the office hours, the end time of the others is not printed to the file except for the last entered office hour.
When I write another code with the same logic, it writes to the file properly, but not in this project. I tried using getchar() but it did not solve my problem. I think the problem is directly in the store_office_hours function, but I can’t understand what it is caused by.
For example, when I expect the office hours to be written like this:
1 Monday 2 p.m. 3 p.m.
2 Friday 4 p.m. 7 p.m.
3 Thursday 5 p.m. 9 p.m.
the data is written to the file like this:
1 Monday 2 p.m.
2 Friday 4 p.m.
3 Thursday 5 p.m. 9 p.m.
omrlv is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.