|
发表于 2023-12-27 13:36:06
|
显示全部楼层
要将修改后的信息保存到txt文件中,可以按照以下步骤进行操作:
1. 在update()函数前声明一个全局变量,用于存储txt文件的路径:- char *filename = "employee.txt";
复制代码 2. 在update()函数中,找到匹配姓名的学生节点后,将新的信息写入txt文件中:- FILE *file = fopen(filename, "w");
- if (file == NULL) {
- printf("文件打开失败!\n");
- return;
- }
- current = head;
- while (current != NULL) {
- fprintf(file, "%d\t%s\t%s\t%f\n", current->id, current->name, current->password, current->salary);
- current = current->next;
- }
- fclose(file);
- printf("修改成功!\n");
- return;
复制代码 3. 这样,每次修改成功后,都会将链表中的所有信息重新写入txt文件中,从而实现保存修改后的信息。注意,这种方法会覆盖原有的txt文件内容。
完整代码如下所示:- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct Employee {
- int id; // 工号
- char name[100]; // 姓名
- char password[100]; // 密码
- float salary; // 工资
- struct Employee *next; // 下一个节点指针
- } Employee;
- Employee *head = NULL;
- void update() {
- char name[100]; // 姓名字符串
- printf("请输入要修改信息的学生姓名:\n");
- scanf("%s", name);
- Employee *current = head; // 当前节点指针
- // 遍历链表,查找匹配姓名的学生节点
- while (current != NULL) {
- if (strcmp(current->name, name) == 0) {
- printf("请输入新的工号:\n");
- scanf("%d", &(current->id));
- printf("请输入新的密码:\n");
- scanf("%s", current->password);
- printf("请输入修改的名字:\n");
- scanf("%s", current->name);
- printf("请输入修改的工资:\n");
- scanf("%f", &(current->salary));
-
- FILE *file = fopen("employee.txt", "w");
- if (file == NULL) {
- printf("文件打开失败!\n");
- return;
- }
- Employee *tmp = head;
- while (tmp != NULL) {
- fprintf(file, "%d\t%s\t%s\t%f\n", tmp->id, tmp->name, tmp->password, tmp->salary);
- tmp = tmp->next;
- }
-
- fclose(file);
- printf("修改成功!\n");
- return; // 修改成功后直接返回
- }
- current = current->next;
- }
-
- printf("未找到该学生信息!\n");
- }
- int main() {
- // 读取txt文件中的信息到链表中
- FILE *file = fopen("employee.txt", "r");
- if (file == NULL) {
- printf("文件打开失败!\n");
- return 0;
- }
- Employee *current = NULL;
- while (!feof(file)) {
- Employee *node = (Employee *)malloc(sizeof(Employee));
- fscanf(file, "%d\t%s\t%s\t%f\n", &(node->id), node->name, node->password, &(node->salary));
- node->next = NULL;
-
- if (head == NULL) {
- head = node;
- } else {
- current->next = node;
- }
- current = node;
- }
- fclose(file);
- update();
- // 释放链表内存
- current = head;
- while (current != NULL) {
- Employee *tmp = current;
- current = current->next;
- free(tmp);
- }
- return 0;
- }
复制代码
请注意,上述代码仅演示了如何将修改后的信息写入txt文件中,并没有考虑到输入信息时的错误处理和链表的其他操作。在实际应用中,还需要根据具体需求进行补充和修改。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|