簡體   English   中英

從具有結構數組的CSV文件中讀取

[英]Reading from a CSV file with a structure array

我是C編程的新手,我想嘗試從CSV文件中讀取並打印出來。 我的CSV文件的格式為:

指數,國家,年,死亡率

1個世界

         50s     36
         60s     29
         70s     22

2非洲

         50s     34

湯加209

         50s     49
         60s     67

等等...

我不確定如何讀取CSV文件的末尾,因此我的代碼輸出最多只能打印到索引143,而當前的CSV文件最多可以打印到204。有人可以指導我嗎?

void readRecords(){
    FILE *fptr;
    int i,j,k;
    char line[200], hold[10];

    if((fptr=fopen("data.csv","r"))==NULL){
        printf("Cannot open input file data.csv\n");
    }

    else{
        for(i=0;i<999;i++){
            fgets(line, 200, fptr);

            j=0;
            k=0;
            while (line[j] != ','){     // This while loop extract the country name until a comma is detected
                hold[k++] = line[j++];  // Simply copy all character from each line to the country
            }
            hold[k]='\0';
            myRecords[i].index=atoi(hold);
            j++;


            k=0;
            while (line[j] != ','){     // This while loop extract the country name until a comma is detected
                myRecords[i].country[k++] = line[j++];  // Simply copy all character from each line to the country
            }
            myRecords[i].country[k]='\0';
            j++;


            k=0;
            while (line[j] != ','){     // This while loop extract the country name until a comma is detected
                hold[k++] = line[j++];  // Simply copy all character from each line to the country
            }
            hold[k]='\0';
            myRecords[i].year=atoi(hold);
            j++;


            k=0;
            while (line[j] != ','){     // This while loop extract the country name until a comma is detected
                hold[k++] = line[j++];  // Simply copy all character from each line to the country
            }
            hold[k]='\0';
            myRecords[i].deathrate=atoi(hold);
            j++;

        }

        }
        fclose(fptr);
    }

另一種選擇是簡單地單步執行fgetsgetline用指針讀取的行,並用\\0字符替換逗號,並在行下逐步讀取每個變量。 給定您的數據文件,這是一個有效的實現:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[]) {

    if (argc < 2) {
        fprintf (stderr, "error: insufficient input, usage: %s <filename>\n", argv[0]);
        return 1;
    }
    FILE *fptr;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    char *p = NULL;
    char *start = NULL;

    int index = 0;
    char *country;
    int years = 0;
    int deaths = 0;

    if ((fptr=fopen (argv[1],"r")) == NULL) {
        fprintf(stderr, "Cannot open input file %s\n", argv[1]);
    }

    while ((read = getline(&line, &len, fptr)) != -1)
    {
        p = line;

        while (*p != ',' && *p != 0) p++;
        *p = '\0';
        index = atoi (line);
        start = ++p;
        while (*p != ',' && *p != 0) p++;
        *p = '\0';
        country = strdup (start);
        start = ++p;
        while (*p != ',' && *p != 0) p++;
        *p = '\0';
        years = atoi (start);
        start = ++p;
        deaths = atoi (start);

        printf ("idx: %3d   country: %12s  years: %3d  deaths: %3d\n",
                index, country, years, deaths);
    }

    free(line);

    return 0;
}

現在,以格式輸入.csv文件:

1,world,50s,36
1,world,60s,65
1,world,70s,58
2,africa,50s,37
2,africa,60s,66
2,africa,70s,59
207,tonga,50s,37
207,tonga,60s,66
207,tonga,70s,59

您的輸出將是:

idx:   1   country:        world  years:  50  deaths:  36
idx:   1   country:        world  years:  60  deaths:  65
idx:   1   country:        world  years:  70  deaths:  58
idx:   2   country:       africa  years:  50  deaths:  37
idx:   2   country:       africa  years:  60  deaths:  66
idx:   2   country:       africa  years:  70  deaths:  59
idx: 207   country:        tonga  years:  50  deaths:  37
idx: 207   country:        tonga  years:  60  deaths:  66
idx: 207   country:        tonga  years:  70  deaths:  59

任一種方式都差不多。 使用strtok或只是逐步進入緩沖區並直接閱讀所需內容。 如果您花時間仔細閱讀代碼。 您將看到它所做的所有操作都被讀取,直到遇到逗號為止,用\\0替換逗號,從開始(或開始)讀取以獲取所需的信息,將指針前進1,設置新的“開始”點,然后然后一直重復向下直到緩沖區。 讀取“死亡”之后,最后一個循環確保已讀取該行中的所有字符。 getline讀取下一行,並繼續直到在.csv文件中無法讀取更多行為止。 我希望這有幫助。 (如果不明顯,可以在命令行中給它csv文件名:

$ readcsv dat.csv

您已經有了數據,並已將其解析為上述變量。 如果要使用結構,則可以簡單地將存儲類型從公用變量更改為結構數據類型。 與以下類似的操作適用於結構數組。

int recs = 0;

struct _stats { 
    int index;
    char *country;
    int years;
    int deaths;
};

struct _stats *stats[100];
struct _stats *statsptr = NULL;

if ((fptr=fopen (argv[1],"r")) == NULL) {
    fprintf(stderr, "Cannot open input file %s\n", argv[1]);
}

while ((read = getline(&line, &len, fptr)) != -1) {

    p = line;
    statsptr = malloc (sizeof (struct _stats));

    while (*p != ',' && *p != 0) p++;
    *p = '\0';
    statsptr->index = atoi (line);
    start = ++p;

    while (*p != ',' && *p != 0) p++;
    *p = '\0';
    statsptr->country = strdup (start);
    start = ++p;

    while (*p != ',' && *p != 0) p++;
    *p = '\0';
    statsptr->years = atoi (start);
    start = ++p;

    statsptr->deaths = atoi (start);

    stats[recs] = statsptr;
    recs++;

}

int iter = 0;
for (iter = 0; iter < recs; iter++) {
    printf ("idx: %3d   country: %12s  years: %3d  deaths: %3d\n",
            stats[iter]->index,
            stats[iter]->country,
            stats[iter]->years,
            stats[iter]->deaths);
}

除了最初聲明結構的最大指針數之外,您還需要使用動態數據類型,例如鏈表。 (超出了本討論的范圍)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM