The program asks user to input some records (structures) if necessary and appends them to the existing file or creates a new file if there isn't any, then lists the contents of the file.
#include <stdio.h>
#include <string.h>
#define N 25
int main() {
struct studrec {
char name[20], surname[20], sex, date[12];
} students[N];
int i, count = 0;
char another;
FILE *fileptr;
for (i = 0; i < 10; i++) {
puts("Press y to continue without adding new records");
another = getchar();
if (another == 'y' || another == 'Y') break;
while ((another = getchar()) != '\n' && another != EOF);
puts("Input info");
puts("Name: ");
if (fgets(students[i].name, sizeof(students[i].name), stdin) == NULL) return 1;
students[i].name[strlen(students[i].name)-1] = '\0';
puts("Surname: ");
if (fgets(students[i].surname, sizeof(students[i].surname), stdin) == NULL) return 1;
students[i].surname[strlen(students[i].surname)-1] = '\0';
puts("Sex (m/f): ");
students[i].sex = getchar();
while ((another = getchar()) != '\n' && another != EOF);
puts("Date (dd.mm.yyyy): ");
if (fgets(students[i].date, sizeof(students[i].date), stdin) == NULL) return 1;
students[i].date[strlen(students[i].date)-1] = '\0';
while ((another = getchar()) != '\n' && another != EOF);
}
count = i;
fileptr = fopen("students.txt", "a+");
for (i = 0; i < count; i++) fwrite(&students, sizeof(students), 1, fileptr);
rewind(fileptr);
for (i = 0; (another = fgetc(fileptr)) != EOF && i < N; i++) {
fseek(fileptr, -1, SEEK_CUR);
fread(&students, sizeof(students), 1, fileptr);
}
fclose(fileptr);
count = i;
for (i = 0; i < count; i++) printf("%20s%20s%4c%15s\n", students[i].name, students[i].surname, students[i].sex, students[i].date);
return 0;
}
Everything works normally when writing to a new file. Output:
...input procedure...
Press y to continue without adding new records
y
Liam James m 12.03.1987
Abbey Trueman f 23.07.1943
Hugo Brown m 13.05.1947
But then if I run it again and try to append another record to the existing file the program fails:
...input procedure...
Press y to continue without adding new records
y
Nadia Rachmonoff f 12.07.1934
O|u
�u � u
� E�u
It seems that the new record is put in students[0] and all the other elements are erased. What am I doing wrong? Maybe there's something wrong with the &students pointer. I tried with &students[i] but it returned "segmentation fault" after the first iteration. As I understand the &students address is "automatically" incremented to the next element after every fread/fwrite. If it wasn't so the program would not work correctly on the first run.