c - How to parse a file that contains a long list of numbers in each line? -


i have file below:

1 2 300 500 5 117 5 90 45 34 ---- -------------- 34566

7 8 16 8 39 167 80 90 38 4555

and on how each numbers , store 2-dimensional array?

so far can read line using fgets() function.

file *fp = null; char buffer[1024];  fp = fopen("input.txt","r");  if(fp!=null) {   while(fgets(buffer,1024,fp)!=null)   {     // need here     }   } 

is there method of solving (better this) rather using fgets()?

#include <stdio.h> #include <stdlib.h>  int main(void){     //either two-pass or ensure dynamically allocate , expand `realloc` if size of array can't determined in advance,       static int array[20][20];     int row=0;     file *fp = null;     char buffer[1024];     fp = fopen("input.txt","r");      if(fp!=null) {         while(fgets(buffer,1024,fp)!=null){             char *p = buffer, *endp;             long num;             int col = 0;             do{                 num = strtol(p, &endp, 10);                 if(*endp == ' ' || *endp == '\n' || *endp == '\0'){                     array[row][col++] = num;                 }                 p = endp + 1;             }while(*endp != '\n' && *endp != '\0');             ++row;         }         fclose(fp);     }     return 0; } 

Comments

Popular posts from this blog

wireshark - USB mapping with python -

c++ - nodejs socket.io closes connection before upgrading to websocket -

Deploying Qt Application on Android is really slow? -