繁体   English   中英

从C中的文件中读取逗号分隔的数字

[英]Read comma separated numbers from a file in C

我在尝试使用逗号分隔的数字读取文件时遇到问题,我希望在这样的文件中创建一个创建整数数组的函数(不知道数组最初有多少参数):

1,0,3,4,5,2
3,4,2,7,4,10
1,3,0,0,1,2

等等。 我想要的结果是这样的

int v[]={1,0,3,4,5,2}

对于文件中的每一行(显然都有每行中的值),所以我可以将这个数组添加到矩阵中。 我尝试使用fscanf,但我似乎无法让它停在每一行的末尾。 我也尝试了fgets,strtok以及我在互联网上发现的许多其他建议,但我不知道该怎么做!

我在32位机器上使用Eclipse Indigo。

使用以下代码,您将CSV存储到多维数组中:

/* Preprocessor directives */
#include <stdio.h>
#include <stdlib.h>

#define ARRAYSIZE(x)  (sizeof(x)/sizeof(*(x)))

const char filename[] = "file.csv";
   /*
    * Open the file.
    */
   FILE *file = fopen(filename, "r");
   if ( file )
   {
      int array[10][10];
      size_t i, j, k;
      char buffer[BUFSIZ], *ptr;
      /*
       * Read each line from the file.
       */
      for ( i = 0; fgets(buffer, sizeof buffer, file); ++i )
      {
         /*
          * Parse the comma-separated values from each line into 'array'.
          */
         for ( j = 0, ptr = buffer; j < ARRAYSIZE(*array); ++j, ++ptr )
         {
            array[i][j] = (int)strtol(ptr, &ptr, 10);
         }
      }
      fclose(file);
#include <stdio.h>
#include <stdlib.h>

int main(){
    FILE *fp;
    int data,row,col,c,count,inc;
    int *array, capacity=10;
    char ch;
    array=(int*)malloc(sizeof(int)*capacity);
    fp=fopen("data.csv","r");
    row=col=c=count=0;
    while(EOF!=(inc=fscanf(fp,"%d%c", &data, &ch)) && inc == 2){
        ++c;//COLUMN count
        if(capacity==count)
            array=(int*)realloc(array, sizeof(int)*(capacity*=2));
        array[count++] = data;
        if(ch == '\n'){
            ++row;
            if(col == 0){
                col = c;
            } else if(col != c){
                fprintf(stderr, "format error of different Column of Row at %d\n", row);
                goto exit;
            }
            c = 0;
        } else if(ch != ','){
            fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row);
            goto exit;
        }
    }
    {   //check print
        int i,j;
//      int (*matrix)[col]=array;
        for(i=0;i<row;++i){
            for(j=0;j<col;++j)
                printf("%d ", array[i*col + j]);//matrix[i][j]
            printf("\n");
        }
    }
exit:
    fclose(fp);
    free(array);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM