程序要求用户输入一些记录(结构),如果有必要并将它们附加到现有文件或创建一个新文件(如果没有),然后列出该文件的内容。追加到C中的文件,读取到结构数组
#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;
}
写入新文件时一切正常。 输出:
...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
不过,如果我再次运行它,并尝试另一条记录追加到现有文件的程序失败:
...input procedure...
Press y to continue without adding new records
y
Nadia Rachmonoff f 12.07.1934
O|u
�u � u
� E�u
看来,新的记录被放在学生[0 ]并且所有其他元素都被删除。 我在做什么错?可能是&学生指针有问题。我尝试了& students [i],但它在第一次迭代后返回了“分段错误”。据我所知&学生地址在每次fread/fwrite后自动递增到下一个元素。如果不是这样,程序在第一次运行时就不能正常工作。
为什么你写的*生*到文件*计数*次? – Beginner