[英]Read CSV file to a 2D array on C
I have a CSV file , but is separate by semicolon , with integers from 1 to 99 and I'd like to put these numbers on a matrix .I'm using fget() but it don't know how to do to read the hole number (not just 2 and 6 instead of 26)我有一个 CSV 文件,但用分号分隔,整数从 1 到 99,我想将这些数字放在矩阵上。我正在使用 fget() 但它不知道如何读取孔号(不只是 2 和 6 而不是 26)
my code:我的代码:
for(i=0;i<100;i++){
for(j=0;j<100;j++){
mat[i][j] = fget(rawdata);;
}
}
If the data is separated by ;
如果数据由
;
分隔, you can use the strtok
method of string.h
. ,您可以使用
string.h
的strtok
方法。
#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 ;
}
I found a way to do it:我找到了一种方法:
for(i=0;i<100;i++){
for(j=0;j<100;j++){
fscanf(rawdata,"%i",&temp);
mat[i][j] = temp;
}
}
thanks to Jongware tip感谢 Jongware 提示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.