MST

星途 面试题库

面试题:C语言fscanf和fprintf在混合数据结构文件处理中的应用

假设有一个文件存储了一系列的结构体数据,结构体定义如下: ```c struct Data { int id; char name[50]; double value; struct { int subId; char subName[30]; } sub; }; ``` 文件中的数据是通过fprintf写入的,现在要求使用fscanf正确读取这些数据,并将所有数据存储到一个链表中。链表节点结构自定义。在读取和存储过程中,要处理好内存分配和释放问题,防止内存泄漏。请编写完整的C语言代码实现该功能。
19.1万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 定义结构体
struct Data {
    int id;
    char name[50];
    double value;
    struct {
        int subId;
        char subName[30];
    } sub;
};

// 定义链表节点
typedef struct Node {
    struct Data data;
    struct Node *next;
} Node;

// 创建新节点
Node* createNode(struct Data data) {
    Node *newNode = (Node*)malloc(sizeof(Node));
    if (newNode == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 读取文件并构建链表
Node* readFileAndCreateList(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("fopen");
        return NULL;
    }

    Node *head = NULL;
    Node *tail = NULL;
    struct Data tempData;

    while (fscanf(file, "%d %49s %lf %d %29s", &tempData.id, tempData.name, &tempData.value, &tempData.sub.subId, tempData.sub.subName) != EOF) {
        Node *newNode = createNode(tempData);
        if (head == NULL) {
            head = newNode;
            tail = newNode;
        } else {
            tail->next = newNode;
            tail = newNode;
        }
    }

    fclose(file);
    return head;
}

// 释放链表内存
void freeList(Node *head) {
    Node *current = head;
    Node *next;
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
}

int main() {
    const char *filename = "data.txt";
    Node *list = readFileAndCreateList(filename);

    // 这里可以对链表进行其他操作

    freeList(list);
    return 0;
}