论坛网站开发语言,wordpress 会员名字,网站前面的小图标怎么做,wordpress图片模糊C语言实战案例#xff1a;文件操作与数据结构案例目标#xff1a;
实现一个学生信息管理系统#xff0c;包含文件读写、链表操作和基本增删改查功能。文件读写与链表结合定义学生结构体并创建链表#xff1a;typedef struct Student {int id;char name[50];float score;str…C语言实战案例文件操作与数据结构案例目标实现一个学生信息管理系统包含文件读写、链表操作和基本增删改查功能。文件读写与链表结合定义学生结构体并创建链表typedef struct Student { int id; char name[50]; float score; struct Student *next; } Student;文件写入函数示例void saveToFile(Student *head, const char *filename) { FILE *file fopen(filename, w); if (!file) return; Student *current head; while (current ! NULL) { fprintf(file, %d %s %.2f\n, current-id, current-name, current-score); current current-next; } fclose(file); }动态内存管理从文件加载数据到链表Student* loadFromFile(const char *filename) { FILE *file fopen(filename, r); if (!file) return NULL; Student *head NULL, *tail NULL; while (!feof(file)) { Student *newNode (Student*)malloc(sizeof(Student)); if (fscanf(file, %d %s %f, newNode-id, newNode-name, newNode-score) 3) { newNode-next NULL; if (!head) head newNode; else tail-next newNode; tail newNode; } else { free(newNode); break; } } fclose(file); return head; }实用功能实现链表插入与删除操作void insertStudent(Student **head, int id, const char *name, float score) { Student *newNode (Student*)malloc(sizeof(Student)); newNode-id id; strcpy(newNode-name, name); newNode-score score; newNode-next *head; *head newNode; } void deleteStudent(Student **head, int id) { Student *temp *head, *prev NULL; while (temp ! NULL temp-id ! id) { prev temp; temp temp-next; } if (temp NULL) return; if (prev NULL) *head temp-next; else prev-next temp-next; free(temp); }高级应用示例排序功能实现冒泡排序void sortByScore(Student **head) { if (!*head || !(*head)-next) return; int swapped; Student *ptr1; Student *lptr NULL; do { swapped 0; ptr1 *head; while (ptr1-next ! lptr) { if (ptr1-score ptr1-next-score) { // 交换数据域 Student temp *ptr1; ptr1-id ptr1-next-id; strcpy(ptr1-name, ptr1-next-name); ptr1-score ptr1-next-score; ptr1-next-id temp.id; strcpy(ptr1-next-name, temp.name); ptr1-next-score temp.score; swapped 1; } ptr1 ptr1-next; } lptr ptr1; } while (swapped); }错误处理增强增加文件操作安全检查Student* safeLoad(const char *filename) { FILE *file fopen(filename, r); if (!file) { perror(Error opening file); return NULL; } // ...其余加载逻辑 if (ferror(file)) { perror(Error reading file); clearerr(file); fclose(file); return NULL; } fclose(file); return head; }该案例完整实现了文件持久化存储、动态内存管理、链表操作等核心功能可作为C语言中级练习的典型范例。实际开发时可进一步扩展搜索功能、界面交互等模块。