Programmer's Blog

Programmer's reference

Monthly Archives: August 2016

[C] Returnable 2D array and readfile

char** create2DCharArray(int m, int n)
{
   char* values = calloc(m*n, sizeof(char));
   char** rows = malloc(n*sizeof(char*));
   int i;
   for (i=0; i<n; ++i)
   {
       rows[i] = values + i*m;
   }
   return rows;
}

void destroy2DCharArray(char** arr)
{
   free(*arr);
   free(arr);
}

char** readFileInto2DArray ( const char* fileName )
{
   FILE *f;
   f = fopen(fileName,"r");
   char ch, strr[32767], *str;
   int row = 0, column = 0, i = 0, j = 0;
   while(fgets(strr, sizeof strr, f))
   {
      row++;
      if(column < strlen(strr) )
           column = strlen(strr);
   }
   rewind(f);
   char** arr = create2DCharArray(column,row);
   while(i < row)
   {
     do
     {
        ch = fgetc(f);
        if ( ch == '\r')
        ch = fgetc(f);
        arr[i][j] = ch;
        j++;
     }
     while( !( ch == '\n' || ch == EOF ) );
     arr[i][--j] = '\0';
     i++;
     j = 0;
   }
   fclose(f);
   return arr;
}
Advertisements