将CSV文件读取到C上的2D数组

gdl*_*dlm 2 c csv file

我有一个CSV文件,但是以分号分隔,整数从1到99,我想将这些数字放在矩阵上.我使用的是fget(),但它不知道如何阅读孔号(不只是2和6而不是26)

我的代码:

for(i=0;i<100;i++){
    for(j=0;j<100;j++){
        mat[i][j] = fget(rawdata);;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sub*_*bbu 5

如果数据是分开的;,则可以使用strtok方法string.h.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
   char buffer[1024] ;
   char *record,*line;
   int i=0,j=0;
   int mat[100][100];
   FILE *fstream = fopen("\myFile.csv","r");
   if(fstream == NULL)
   {
      printf("\n file opening failed ");
      return -1 ;
   }
   while((line=fgets(buffer,sizeof(buffer),fstream))!=NULL)
   {
     record = strtok(line,";");
     while(record != NULL)
     {
     printf("record : %s",record) ;    //here you can put the record into the array as per your requirement.
     mat[i][j++] = atoi(record) ;
     record = strtok(NULL,";");
     }
     ++i ;
   }
   return 0 ;
 }
Run Code Online (Sandbox Code Playgroud)