fgets()" />

C語言讀取CSV文件


讀取CSV文件

思路很簡單,利用 f g e t s ( ) 函數來逐行讀取,對每一行進行字符串拆分操作 並存入相應的二維數組里面即可

假設一個csv文件如下所示

x1,x2,x3,x4,y
3.6216,8.6661,-2.8073,-0.44699,0
4.5459,8.1674,-2.4586,-1.4621,0
3.866,-2.6383,1.9242,0.10645,0
3.4566,9.5228,-4.0112,-3.5944,1
0.32924,-4.4552,4.5718,-0.9888,1
4.3684,9.6718,-3.9606,-3.1625,1

c語言代碼

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

void get_two_dimension(char* line, double** data, char *filename);
void print_two_dimension(double** data, int row, int col);
int get_row(char *filename);
int get_col(char *filename);

int main()
{
    char filename[] = "C:\\Users\\...\\...\\csvtest.csv";
    char line[1024];
    double **data;
    int row, col;
    row = get_row(filename);
    col = get_col(filename);
    data = (double **)malloc(row * sizeof(int *));
    for (int i = 0; i < row; ++i){
        data[i] = (double *)malloc(col * sizeof(double));
    }//動態申請二維數組 
    get_two_dimension(line, data, filename);
    printf("row = %d\n", row);
    printf("col = %d\n", col);
    print_two_dimension(data, row, col);
}

void get_two_dimension(char* line, double** data, char *filename)
{
    FILE* stream = fopen(filename, "r");
    int i = 0;
    while (fgets(line, 1024, stream))//逐行讀取
    {
        int j = 0;
        char *tok;
        char* tmp = strdup(line);
        for (tok = strtok(line, ","); tok && *tok; j++, tok = strtok(NULL, ",\n")){
            data[i][j] = atof(tok);//轉換成浮點數 
        }//字符串拆分操作 
        i++;
        free(tmp);
    }
    fclose(stream);//文件打開后要進行關閉操作
}

void print_two_dimension(double** data, int row, int col)
{
    int i, j;
    for(i=1; i<row; i++){
        for(j=0; j<col; j++){
            printf("%f\t", data[i][j]);
        }
        printf("\n");
    }//打印的時候不打印第一行,第一行全是字符
}

int get_row(char *filename)
{
    char line[1024];
    int i;
    FILE* stream = fopen(filename, "r");
    while(fgets(line, 1024, stream)){
        i++;
    }
    fclose(stream);
    return i;
}

int get_col(char *filename)
{
    char line[1024];
    int i = 0;
    FILE* stream = fopen(filename, "r");
    fgets(line, 1024, stream);
    char* token = strtok(line, ",");
    while(token){
        token = strtok(NULL, ",");
        i++;
    }
    fclose(stream);
    return i;
}

運行結果

row = 7
col = 5
3.621600        8.666100        -2.807300       -0.446990       0.000000
4.545900        8.167400        -2.458600       -1.462100       0.000000
3.866000        -2.638300       1.924200        0.106450        0.000000
3.456600        9.522800        -4.011200       -3.594400       1.000000
0.329240        -4.455200       4.571800        -0.988800       1.000000
4.368400        9.671800        -3.960600       -3.162500       1.000000

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: