回复 9楼 TonyDeng
1 1 1 18177286824 1 2 2 2 18177286824 2把前面三个1改成2
#include <cstdio> #include <cstdlib> #include <conio.h> struct Student { char Name[11]; char Sex; long Birthday; Student* next; }; void Init(void); void Save_Data(const char* filename, Student* students, size_t count); Student* Load_Data(const char* filename); void Update_Data(const char* filename, const Student* student, size_t index); void List_Students(Student* students); void Show_Student(const Student* student); const char* FileName = "Students.DAT"; int main(void) { Init(); Student* students = Load_Data(FileName); List_Students(students); printf_s("Now update record 2\n"); students->next->Birthday = 19921014; students->next->Sex = 0; Update_Data(FileName, students->next, 2); // 用指针students-next所指向的数据,刷写文件中的第2条记录 students = Load_Data(FileName); List_Students(students); printf_s("\nPress any key to continue..."); _getch(); return EXIT_SUCCESS; } void Init(void) { Student students[3] = { { "张三", 0, 19920312 }, { "李四", 1, 19921004 }, { "王五", 0, 19930120 } }; Save_Data(FileName, students, _countof(students)); } void Save_Data(const char* filename, Student* students, size_t count) { FILE* file; if (fopen_s(&file, filename, "wb") == 0) { fwrite(&count, sizeof(count), 1, file); for (size_t index = 0; index < count; ++index) { fwrite(&students[index], sizeof(Student), 1, file); } fclose(file); } else { printf_s("File %s create failure.\n", filename); } } Student* Load_Data(const char* filename) { FILE* file; Student* head = NULL; if (fopen_s(&file, filename, "rb") == 0) { size_t count; Student* previous = NULL; fread(&count, sizeof(count), 1, file); for (size_t index = 0; index < count; ++index) { Student* stu = (Student*)calloc(1, sizeof(Student)); if (stu != NULL) { (previous != NULL) ? (previous->next = stu) : (head = stu); fread(stu, sizeof(Student), 1, file); previous = stu; } else { printf_s("Memory allocation error.\n"); break; } } fclose(file); } else { printf_s("File %s read failure.\n", filename); } return head; } void Update_Data(const char* filename, const Student* student, size_t index) { FILE* file; if (fopen_s(&file, filename, "rb+") == 0) { size_t count; fread(&count, sizeof(count), 1, file); fseek(file, (index - 1) * sizeof(Student), SEEK_CUR); fwrite(student, sizeof(Student), 1, file); fclose(file); } else { printf_s("File %s update failure.\n", filename); } } void List_Students(Student* students) { while (students != NULL) { Show_Student(students); students = students->next; } } void Show_Student(const Student* student) { printf_s("%-10s %2s %u\n", student->Name, (student->Sex == 0) ? "男" : "女", student->Birthday); }