如何使用c语言将.csv文件中的数据读取到多维数组?

时间:2014-07-03 08:24:29

标签: c arrays matlab csv

在matlab中我们可以使用代码来完成:

a= csvread('filename.csv');

但是使用C编程我使用了以下代码,但它不起作用请帮助:

int main(){
int i,j,temp,m1=0,n=0;
//CSV file reading
int ch;
FILE *fp;
fp = fopen("filename.csv","r"); // read mode
if( fp == NULL )
{
  perror("Error while opening the file.\n");
  exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fp) ) != EOF )
  {printf("%d",ch);}
fclose(fp);
return 0;
}

mat[i][j] = ch;
int m1 = i;
int n = j;
}

请帮忙!

1 个答案:

答案 0 :(得分:0)

好的,这还没有经过广泛测试,但它应该读取一个具有整数值的csv文件,并将它们存储在(n×m)矩阵中。

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

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

    //CSV file reading
    int rowMaxIndex,columnMaxIndex;
    int **mat;
    int *matc;
    int i,j,idx;

    char part[1024];
    char *token;
    FILE *fp;
    fp = fopen("filename.csv","r"); // read mode
    if(fp == NULL){
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }

    // count loop
    rowMaxIndex = 0;
    columnMaxIndex = 0;
    while(fgets(part,1024,fp) != NULL){
        token = NULL;

        while((token = strtok((token == NULL)?part:NULL,",")) != NULL){
            if(rowMaxIndex == 0){ // only want to increment column count on first loop
                columnMaxIndex++;
            }
            for(idx = 0;idx<strlen(token);idx++){
                if(token[idx] == '\n'){ // this assumes there will be a \n (LF) at the end of the line
                    rowMaxIndex++;
                    break;
                }
            }
        }
    }

    // allocate the matrix
    matc = malloc(rowMaxIndex*columnMaxIndex*sizeof(int));
    mat = malloc(rowMaxIndex*sizeof(int*));

    for(idx = 0;idx<rowMaxIndex;idx++){
        mat[idx] = matc+idx*columnMaxIndex;
    }

    // rewind the file to the beginning
    rewind(fp);

    // read loop
    i = j = 0;
    while(fgets(part,1024,fp) != NULL){
        token = NULL;
        while((token = strtok((token == NULL)?part:NULL,",")) != NULL){
            mat[i][j] = atoi(token);
            j = (j+1)%columnMaxIndex;
        }
        i++;
    }

    fclose(fp);
    return 0;
}