程序要求用戶輸入一些記錄(結構),如果有必要並將它們附加到現有文件或創建一個新文件(如果沒有),然後列出該文件的內容。追加到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