如何将csv文件读入c的结构链接列表中

问题描述 投票:0回答:1

我是这里的新手,也是一般编程人员(请注意管理员和编程大师,对我来说很容易,谢谢),我正在用C做学校作业,其中涉及一个小的程序,该程序将一个csv文件单独读取链表,其中数据是结构,然后显示它,然后对其进行排序并将其写到文本文件中,等等。

我现在遇到的问题是阅读功能或显示功能:结果是数据以相反的顺序被读取或显示,并且向下移动了一行。]

我已经用力地敲了一下头,但是现在我已经没时间了,我想在这里问一下,也许是想从新鲜的眼睛中得到一些反馈。作为链接附加的是要读取的文件内容和程序输出的屏幕截图(显然,因为我是新用户,所以我无法将照片直接上传到网站。)在此先感谢

以下是相关代码行:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <conio.h>
#include <string.h>


// DEFINE
#define CSV_FILE_TO_READ "TPP_TP_Data_2019_base.csv"


// ============================
// GLOBAL VARIABLES


struct node
{
    char Name[50];
    char Firstname[50];
    char Initials[10];
    char Mobile[30];
    char Class[50];
    char InitialSort[50]; // change into int
    char RandomSort[50];  // change into float

    struct node *next;
} *head;


// ============================
// FONCTION PROTOTYPE DECLARATIONS

void Read();
void Display();


// ============================
// MAIN

int main()
{

    Read();
    Display();


    return 0;
}

// ============================
// FUNCTIONS

void Read()
{

    FILE *fPointer;
    fPointer = fopen(CSV_FILE_TO_READ,"r");

    if (fPointer == NULL)
    {
        printf("\nCould not open file %s",CSV_FILE_TO_READ);
        return;
    }

    //reading the file and creating liked list

    char parsedLine[100];
    while(fgets(parsedLine, 100, fPointer) != NULL)
    {
        struct node *node = malloc(sizeof(struct node));

        char *getName = strtok(parsedLine, ";");
        strcpy(node->Name, getName);

        char *getFirstname = strtok(NULL, ";");
        strcpy(node->Firstname, getFirstname);

        char *getInitials = strtok(NULL, ";");
        strcpy(node->Initials, getInitials);

        char *getMobile = strtok(NULL, ";");
        strcpy(node->Mobile, getMobile);

        char *getClass = strtok(NULL, ";");
        strcpy(node->Class, getClass);

        char *getInitialSort = strtok(NULL, ";");  // change function into int getter
        strcpy(node->InitialSort, getInitialSort);

        char *getRandomSort = strtok(NULL, ";");  // change function into a float getter
        strcpy(node->RandomSort, getRandomSort);


        node->next = head;
        head = node;

    }

    fclose(fPointer);
}




void Display()  // displays the content of the linked list
{
    struct node *temp;
    temp=head;
    while(temp!=NULL)
    {
        printf("%s %s %s %s %s %s %s \n",temp->Name,temp->Firstname,temp->Initials,temp->Mobile,temp->Class,temp->InitialSort,temp->RandomSort);
        temp = temp->next;
    }
    printf("\n");
    printf("===========================================");

}

output of the program

c csv struct linked-list structure
1个回答
0
投票

创建列表的方式是stack

© www.soinside.com 2019 - 2024. All rights reserved.