微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将文件中的数据解析为c中的链表

如何解决将文件中的数据解析为c中的链表

void save(FrameNode* list)
{
    FILE* fileSaver = NULL;

    fileSaver = fopen("C:\\Users\\magshimim\\Desktop\\test\\savedData.txt","w+");
    FrameNode* curr = list;


    while (curr)
    {
        fprintf(fileSaver,"%s %d %s\n",curr->frame->name,curr->frame->duration,curr->frame->path);
        curr = curr->next;
    }

    fclose(fileSaver);
    printf("Saved successfully!\n");
}

输出文件

1 500 C:\Users\magshimim\Desktop\test\tt.png
2 6969 C:\Users\magshimim\Desktop\test\tt.png

我有一个保存链表的函数,现在它将它保存为输出到由空格和换行符分割的文本文件

保存顺序:名称、持续时间、路径

如何将其加载回链表结构:

// Frame struct
typedef struct Frame
{
    char* name;
    unsigned int    duration;
    char* path;
} Frame;


// Link (node) struct
typedef struct FrameNode
{
    Frame* frame;
    struct FrameNode* next;
} FrameNode;

并按顺序加载它们也很重要

我读过 fscanf() 我尝试用它来解析数据仍然无法做到。

每个frameNode都有一个frame,其中包含数据,frameNode中有next,用于制作链表

我有一个创建 frameNode 的函数

/**
Function will create a frame
input:
image name,duration and path
output:
the image with the updated info
*/
FrameNode* createFrame(FrameNode* head,char name[],char path[],unsigned int duration)
{
    int nameExist = doesNameExist(head,name); //doesNameExist() checks if a name already exists in the linked list returns 1 if a name exist,0 if not

    if (nameExist) 
    {
        printf("Name already exists!\n");
        return 0;
    }

    FrameNode* newFrame = (FrameNode*)malloc(sizeof(FrameNode));
    newFrame->frame = (Frame*)malloc(sizeof(Frame));
    newFrame->frame->name = (char*)malloc(STR_LEN);
    newFrame->frame->path = (char*)malloc(STR_LEN);
    newFrame->frame->duration = (unsigned int*)malloc(sizeof(unsigned int));

    strncpy(newFrame->frame->name,name,STR_LEN);
    strncpy(newFrame->frame->path,path,STR_LEN);
    newFrame->frame->duration = duration;
    newFrame->next = NULL;

    return newFrame;
}

将链表添加到末尾的函数

/**
Function will add an image to the frames
input:
newNode - the new person to add to the list
output:
none
*/
void insertAtEnd(FrameNode* newNode,FrameNode** head)
{
    if (!(*head))
    {
        *head = newNode;
    }
    else
    {
        FrameNode* p = (*head);
        while (p->next)
        {
            p = p->next;
        }
        p->next = newNode;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。