简体   繁体   中英

Read txt file to linked list C

i tried to save my linked list to txt file and load it later . 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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