You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现数组的读取与加载?Facebook Lite项目档案存读问询

嘿,我来帮你搞定这个用户档案持久化的问题!针对你Facebook Lite项目里用profiles[idx]数组存用户档案、用switch做菜单的场景,我整理了一套直接能用的方案,分步骤给你讲清楚。

核心思路:序列化+文件IO

咱们要解决的本质是把内存里的用户数组转换成可存储的格式(序列化),退出时写到文件里;启动时再把文件内容转回到数组里(反序列化)。推荐用JSON格式,因为它能完美匹配用户档案的结构化数据(名字、姓氏、好友列表、年龄),而且不管你用的是C、Java还是Python,都有现成的工具库或者简单实现方式。

具体实现步骤

1. 程序启动时:加载档案到profiles数组

  • 检查存储档案的文件(比如user_profiles.json)是否存在
  • 如果存在,读取文件内容,解析成用户对象,逐个放到profiles数组里,同时更新nop(档案总数)
  • 如果不存在,初始化空数组,nop设为0

2. 用户退出时:保存profiles数组到文件

  • 在switch菜单的退出选项(比如case EXIT)里,先调用保存函数
  • 把profiles数组里的所有用户档案序列化成JSON字符串
  • 把JSON字符串写入到指定文件,覆盖旧内容(做个备份会更稳妥哦)
代码示例(以C语言为例,适配switch场景)

第一步:定义用户结构体

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 好友链表节点
typedef struct FriendNode {
    char friendName[50];
    struct FriendNode* next;
} FriendNode;

// 用户档案结构体
typedef struct UserProfile {
    char firstName[50];
    char lastName[50];
    FriendNode* friendList;
    int age;
} UserProfile;

UserProfile profiles[100]; // 假设最多存储100个用户
int nop = 0; // 当前档案总数

第二步:实现保存函数(JSON序列化)

void saveProfiles() {
    FILE* file = fopen("user_profiles.json", "w");
    if (!file) {
        printf("Error opening file for saving!\n");
        return;
    }

    // 写入JSON数组开头
    fprintf(file, "[\n");
    for (int i = 0; i < nop; i++) {
        fprintf(file, "  {\n");
        fprintf(file, "    \"firstName\": \"%s\",\n", profiles[i].firstName);
        fprintf(file, "    \"lastName\": \"%s\",\n", profiles[i].lastName);
        fprintf(file, "    \"age\": %d,\n", profiles[i].age);
        fprintf(file, "    \"friendList\": [");

        // 遍历好友链表并写入
        FriendNode* current = profiles[i].friendList;
        int isFirst = 1;
        while (current != NULL) {
            if (!isFirst) fprintf(file, ", ");
            fprintf(file, "\"%s\"", current->friendName);
            isFirst = 0;
            current = current->next;
        }
        fprintf(file, "]\n");

        // 最后一个用户不加逗号,保证JSON格式合法
        if (i != nop - 1) fprintf(file, "  },\n");
        else fprintf(file, "  }\n");
    }
    fprintf(file, "]");

    fclose(file);
    printf("Profiles saved successfully!\n");
}

第三步:实现加载函数(JSON反序列化)

void loadProfiles() {
    FILE* file = fopen("user_profiles.json", "r");
    if (!file) {
        printf("No existing profiles found, starting fresh.\n");
        return;
    }

    char buffer[1024];
    int inUser = 0;
    UserProfile tempUser;
    FriendNode** currentFriend = &tempUser.friendList;
    tempUser.friendList = NULL;

    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        // 匹配用户对象开始
        if (strstr(buffer, "{") != NULL) {
            memset(&tempUser, 0, sizeof(tempUser));
            currentFriend = &tempUser.friendList;
            inUser = 1;
        }
        // 匹配用户对象结束,存入数组
        else if (strstr(buffer, "}") != NULL && inUser) {
            profiles[nop++] = tempUser;
            inUser = 0;
        }
        // 解析各个字段
        else if (inUser) {
            char* firstName = strstr(buffer, "\"firstName\":");
            if (firstName) sscanf(firstName, "\"firstName\": \"%[^\"]\"", tempUser.firstName);
            
            char* lastName = strstr(buffer, "\"lastName\":");
            if (lastName) sscanf(lastName, "\"lastName\": \"%[^\"]\"", tempUser.lastName);
            
            char* age = strstr(buffer, "\"age\":");
            if (age) sscanf(age, "\"age\": %d", &tempUser.age);
            
            char* friendList = strstr(buffer, "\"friendList\": [");
            if (friendList) {
                char* friendStart = friendList + strlen("\"friendList\": [");
                char* friendEnd = strstr(friendStart, "]");
                if (friendEnd) {
                    *friendEnd = '\0';
                    char* friendName = strtok(friendStart, ", \"");
                    while (friendName != NULL) {
                        FriendNode* newNode = malloc(sizeof(FriendNode));
                        strcpy(newNode->friendName, friendName);
                        newNode->next = NULL;
                        *currentFriend = newNode;
                        currentFriend = &newNode->next;
                        friendName = strtok(NULL, ", \"");
                    }
                }
            }
        }
    }

    fclose(file);
    printf("Loaded %d profiles successfully!\n", nop);
}

第四步:在菜单switch中调用

#define EXIT 5

void mainMenu() {
    int choice;
    do {
        printf("\n--- Facebook Lite Menu ---\n");
        printf("1. Add User\n");
        printf("2. View User\n");
        printf("3. Add Friend\n");
        printf("4. View Friends\n");
        printf("5. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch(choice) {
            case 1:
                // 这里写添加用户的逻辑
                break;
            case 2:
                // 这里写查看用户的逻辑
                break;
            case 3:
                // 这里写添加好友的逻辑
                break;
            case 4:
                // 这里写查看好友的逻辑
                break;
            case EXIT:
                saveProfiles(); // 退出前先保存档案
                printf("Exiting program...\n");
                break;
            default:
                printf("Invalid choice! Try again.\n");
        }
    } while(choice != EXIT);
}

int main() {
    loadProfiles(); // 程序启动时加载档案
    mainMenu();
    
    // 别忘了释放好友链表的内存,避免内存泄漏
    for (int i = 0; i < nop; i++) {
        FriendNode* current = profiles[i].friendList;
        while (current != NULL) {
            FriendNode* temp = current;
            current = current->next;
            free(temp);
        }
    }
    return 0;
}
额外提示
  • 如果是Java/Python等语言,思路完全一致,用语言自带的JSON工具(比如Python的json模块、Java的Gson)会比手动解析简单得多
  • 生产环境要加更完善的错误处理(比如文件读写失败的重试、JSON解析失败的容错)
  • 如果用户数量较多,建议用SQLite等轻量数据库代替JSON文件,性能和扩展性更好

内容的提问来源于stack exchange,提问作者Shahbaz Malik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:23:26