怎么修改
void deleteEmployee() {int id;
printf("请输入要删除的员工工号:");
scanf("%d", &id);
Employee* current = head;
Employee* prev = NULL;
while (current != NULL && current->id != id) {
prev = current;
current = current->next;
}
if (current == NULL) {
printf("未找到该员工信息!\n");
return;
}
if (prev == NULL) {
head = current->next;
} else {
prev->next = current->next;
}
free(current);
printf("员工信息删除成功!\n");
_save(head);
}
怎么修改是保存在文件里面的内容也删除呢 要实现将内容保存在文件中,并删除文件中的相应内容,可以按照以下步骤进行修改:
1. 在删除员工信息之前,先读取保存在文件中的所有员工信息,并将其存储在链表中。
2. 修改代码中的`deleteEmployee()`函数,添加一个新的局部变量`Employee* temp`,用于遍历链表。
3. 在遍历链表并找到要删除的员工信息后,将`current`指针指向的员工节点从链表中删除。
4. 使用`_save()`函数将更新后的链表重新保存到文件中。
下面是修改后的代码示例:
#include <stdio.h>
#include <stdlib.h>
typedef struct employee {
int id;
struct employee* next;
} Employee;
Employee* head = NULL;
void _save(Employee* list) {
FILE* file = fopen("employees.txt", "w");
if (file == NULL) {
printf("无法打开文件!\n");
return;
}
Employee* current = list;
while (current != NULL) {
fprintf(file, "%d\n", current->id);
current = current->next;
}
fclose(file);
}
void load() {
FILE* file = fopen("employees.txt", "r");
if (file == NULL) {
printf("无法打开文件!\n");
return;
}
int id;
while (fscanf(file, "%d", &id) != EOF) {
Employee* newEmployee = (Employee*)malloc(sizeof(Employee));
newEmployee->id = id;
newEmployee->next = NULL;
if (head == NULL) {
head = newEmployee;
} else {
Employee* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newEmployee;
}
}
fclose(file);
}
void deleteEmployee() {
int id;
printf("请输入要删除的员工工号:");
scanf("%d", &id);
load();// 读取保存的员工信息
Employee* current = head;
Employee* prev = NULL;
Employee* temp = NULL;
while (current != NULL) {
if (current->id == id) {
if (prev == NULL) {
head = current->next;
} else {
prev->next = current->next;
}
temp = current;
current = current->next;
free(temp);// 释放删除的节点
printf("员工信息删除成功!\n");
break;
}
prev = current;
current = current->next;
}
_save(head);// 将更新后的链表保存到文件中
}
int main() {
deleteEmployee();
return 0;
}
在这个示例中,我们新增了一个`load()`函数,用于从文件中加载保存的员工信息,并将其存储在链表中。然后,在删除员工信息之前,调用`load()`函数加载文件中的数据。删除操作完成后,再调用`_save()`函数将更新后的链表保存回文件中。
这样,你就可以实现将内容保存在文件中,并删除文件中对应的员工信息了。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页:
[1]