c - Loading in numbers from a file containing whitespace to a 2d integer array -


i have file of numbers, laid out in 20x20 grid (there exists line break every line). i'm trying figure out how load 2d array of ints in plain c?

here's grid

enter image description here

here's link actual text file

my file i/o knowledge is shaky , kindergarten level @ best.

fscanf version

#include <stdio.h>  int main(void){     file *fp;     int i, j;     int data[20][20];      if(null==(fp=fopen("data.txt","r"))){         perror("file can't open");         return -1;     } /*  slower fgets , strtol     for(i=0;i<20;++i)         for(j=0;j<20;++j)             fscanf(fp, "%d", &data[i][j]); */     for(i=0;i<20;++i)//little difference         fscanf(fp, "%d %d %d %d %d %d %d %d %d %d"                    "%d %d %d %d %d %d %d %d %d %d",             &data[i][0],&data[i][1],&data[i][2],&data[i][3],&data[i][4],             &data[i][5],&data[i][6],&data[i][7],&data[i][8],&data[i][9],             &data[i][10],&data[i][11],&data[i][12],&data[i][13],&data[i][14],             &data[i][15],&data[i][16],&data[i][17],&data[i][18],&data[i][19]);     fclose(fp);     //pickup check      printf("%d\n", data[5][4]);//99     printf("%d\n", data[19][19]);//48      return 0; } 

fgets , strtol version

#include <stdio.h> #include <stdlib.h>  int main(void){     file *fp;     int i, j, wk;     int data[20][20];     char buff[64], *p, *endp;      if(null==(fp=fopen("data.txt","r"))){         perror("file can't open");         return -1;     }     for(i=0;i<20;++i){         fgets(buff, sizeof(buff), fp);         for(j=0, p=buff;j<20;++j, p=endp){             wk = (int)strtol(p, &endp, 10);             if(*endp == ' ' || *endp == '\n' || *endp == '\0'){                 data[i][j] = wk;             }         }     }     fclose(fp);     //pickup check      printf("%d\n", data[5][4]);//99     printf("%d\n", data[19][19]);//48     return 0; } 

not use fscanf or fgets , strtol version. (maybe fast, situation limited.)

#include <stdio.h> #include <ctype.h>  int main(void){     file *fp;     int data[20][20];     int wk, wk2, *ip, *endp = &data[19][19]+1;     char buff[1280]={0}, *cp;      fp=fopen("data.txt","r");     fread(buff, sizeof(buff), 1, fp);     fclose(fp);     ip=&data[0][0];     wk = 0;     for(cp=buff;ip!=endp;++cp){         if(isdigit(*cp)){             wk2 = wk << 1;             wk = (wk2 << 2) + wk2 + (*cp -'0');         } else {             *ip++ = wk;             wk = 0;         }     }     return 0; } 

note:every version of these 3 has short time of unmeasurable.

it meaningless slow , fast, case of reading data of 20 x 20.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -