C语言 将 CSV 文件读取到 C 上的二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20013693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read CSV file to a 2D array on C
提问by gdlm
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);;
}
}
回答by Subbu
If the data is separated by ;, you can use the strtokmethod of string.h.
如果数据以 分隔;,则可以使用 的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 ;
}
回答by gdlm
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 提示

