【问题标题】:How to read data from a .csv file to a multidimentional array using c language?如何使用 c 语言将 .csv 文件中的数据读取到多维数组?
【发布时间】:2014-07-03 08:24:29
【问题描述】:

在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;
}

请帮忙!

【问题讨论】:

  • 几个问题。 csv 中的值是否总是整数?在读取文件之前,您知道文件中的值的数量吗?例如,是否总是说 5 行 4 列?
  • 定义“不起作用”。 (乍一看,您似乎很难实现简单的循环逻辑。)

标签: c arrays matlab csv


【解决方案1】:

好的,这还没有经过广泛的测试,但它应该读取一个包含整数值的 csv 文件并将它们存储在一个 (n x 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;
}

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2015-05-16
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多