void loadUsersFromFile() {
FILE* file = fopen("users.csv", "r");
if (file == NULL) {
printf("Failed to open file.\n");
return;
}
char line[200];
while (fgets(line, sizeof(line), file)) {
// 去除行尾的换行符
if (line[strlen(line) - 1] == '\n') {
line[strlen(line) - 1] = '\0';
}
User* newUser = (User*)malloc(sizeof(User));
// 使用逗号分隔行中的字段
char* token = strtok(line, ",");
newUser->id = atoi(token);
token = strtok(NULL, ",");
strcpy(newUser->username, token);
token = strtok(NULL, ",");
strcpy(newUser->password, token);
token = strtok(NULL, ",");
strcpy(newUser->phone, token);
token = strtok(NULL, ",");
strcpy(newUser->email, token);
// 插入节点到链表中
if (head == NULL || newUser->id < head->id) {
newUser->next = head;
head = newUser;
} else {
User* current = head;
while (current->next != NULL && current->next->id < newUser->id) {
current = current->next;
}
newUser->next = current->next;
current->next = newUser;
}
}
fclose(file);
}
// 将链表中的用户信息写入.csv文件
void saveUsersToFile() {
FILE* file = fopen("users.csv", "w");
if (file == NULL) {
printf("Failed to open file.\n");
return;
}
User* current = head;
while (current != NULL) {
fprintf(file, "%d,%s,%s,%s,%s\n", current->id, current->username, current->password, current->phone, current->email);
current = current->next;
}
fclose(file);
}