简体   繁体   English

读取txt文件到链表C

[英]Read txt file to linked list C

i tried to save my linked list to txt file and load it later .我试图将我的链表保存到 txt 文件并稍后加载。 its for a movie editor project.它用于电影编辑器项目。 the nodes:节点:

// 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;

and i saved it in this way:我以这种方式保存了它:

path小路

duration期间

name名称

path小路

duration期间

name名称

path小路

duration期间

name名称

path小路

duration期间

name名称

... ...

\\n between the data. \\n 之间的数据。

this is my function:这是我的功能:

FrameNode* loadVideo()
{
    FrameNode* head = NULL;
    FrameNode* newNodeFrame = NULL;
    FrameNode* newFrame = NULL;
    FILE* f = NULL;
    char pathP[STR_LEN] = "";
    
    char file[1024] = { 0 };
    char c;

    char path[1000] = "";
    char name[1000] = "";
    char duration[STR_LEN] = "";

    int i = 0;
    int j = 0;

    printf("Enter the path of file to load: ( .txt)\n");
    myFgets(pathP);

    f = fopen(pathP, "r");

    if (f == NULL)
    {
        printf("Error opening file\n");
        return;
    }

    while ((c = (char)fgetc(f)) != EOF)
    {
        file[i] = c;
        i++;
    }

    fclose(f);

    for (i = 0; i < strlen(file); i++)
    {
        while (file[i] != '\n')
        {
            path[j] = file[i];
            i++;
            j++;
        }
        j = 0;
        i++;
        while (file[i] != '\n')
        {
            duration[j] = file[i];
            i++;
            j++;
        }
        j = 0;
        i++;
        while (file[i] != '\n')
        {
            name[j] = file[i];
            i++;
            j++;
        }
        j = 0;

        newFrame = craeteFrame(name, atoi(duration), path);
        FrameNode* newFrameNode = (FrameNode*)malloc(sizeof(FrameNode));

        newFrameNode->frame = newFrame;
        newFrameNode->next = NULL;

        insertAtEnd(&head, newFrameNode);
    }

    return head;
}

its not perfect and it's very ugly.. someone has better option?它并不完美,而且非常丑陋……有人有更好的选择吗? thanks.谢谢。 ..if you have some changes to offer to me about the save in the file its will be good to ..如果您对文件中的保存有一些更改要提供给我,那将很好

Use fgets() to read whole lines at a time.使用fgets()读取整行。 You would still have to deal with memory allocation to hold the contents of those line then.您仍然需要处理内存分配以保存这些行的内容。 However, most POSIX-compliant operating systems also provide the function getline() which reads a line into a buffer it will allocate automatically for you.但是,大多数符合 POSIX 的操作系统还提供函数getline() ,该函数将一行读入缓冲区,它将自动为您分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM