Advertisement
Guest User

Untitled

a guest
Nov 24th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. void get_sizes(char ** file_name,int * r ,int * c)
  2. {
  3.     //getting number of columns and rows
  4.     int flag = 0 ;
  5.     FILE *f;
  6.     f = fopen(file_name,"r");
  7.     if(f != NULL )
  8.     {
  9.          while (!feof(f))
  10.     {
  11.         char ch = fgetc(f);
  12.        if(ch == ' ' && flag == 0)
  13.        {
  14.            *c = *c + 1 ;
  15.  
  16.        }
  17.  
  18.        if(ch == '\n')
  19.       {
  20.           *r = *r + 1 ;
  21.           flag = 1; //flag to stop counting spaces
  22.  
  23.       }
  24.  
  25.     }
  26.  
  27.     fclose(f);
  28.     }
  29.     else
  30.   {
  31.       printf("error reading file");
  32.       exit(-1);
  33.   }
  34.  
  35.  
  36.  
  37. }
  38.  
  39. float ** build_matrix(char ** file_name,int * r ,int * c )
  40. {
  41.   FILE *f;
  42.   float temp[50];
  43.    int rows = *r , columns = *c;
  44.   int counter = 0,i = 0,j = 0;
  45.   //dynamic allocation for matrix
  46.   float **matrix;
  47.     matrix = malloc(sizeof(float*) * columns);
  48.  
  49.     for(i = 0; i < rows; i++) {
  50.         matrix[i] = malloc(sizeof(float*) * columns);
  51.     }
  52.  
  53.     //getting the values in a temporary array
  54.   f = fopen(file_name, "r");
  55.   if(f != NULL )
  56.   {
  57.       while (!feof(f))
  58.     {
  59.  
  60.       fscanf(f,"%f",&temp[counter]);
  61.  
  62.       counter++;
  63.     }
  64.  
  65.     // building the matrix
  66.  
  67.         counter = 0 ;
  68.         for(i = 0; i < *r; i++)
  69.         {
  70.  
  71.             for(j = 0; j < *c; j++)
  72.             {
  73.                 matrix[i][j] = temp[counter];
  74.                 counter++;
  75.             }
  76.  
  77.  
  78.         }
  79.  
  80.  
  81.  
  82.   }
  83.   else
  84.   {
  85.       printf("error reading file");
  86.       exit(-1);
  87.   }
  88.  
  89.  
  90.  
  91.   fclose(f);
  92.   return matrix;
  93.  
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement