9511_project01

project 1 for algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
load_country_codes.c (1907B)
   1 // Carga en el arreglo 'country_codes' los codigos de los paises de el archivo 
   2 // de nombre "COUNTRY_CODES_FILE_NAME" (definido en macros.h) ubicado en el 
   3 // directorio desde el que se ejecuta el programa;
   4 
   5 
   6 #include "load_country_codes.h"
   7 
   8 
   9 status_t load_country_codes(char **country_codes)
  10 {
  11     FILE *fp;
  12 
  13     empty_country_codes(country_codes);
  14 
  15     char *buff;
  16     char buff2[INITIAL_SIZE];
  17     buff2[INITIAL_SIZE] = '\0';
  18 
  19     clean(buff2, INITIAL_SIZE);
  20 
  21     int country_code = 0;
  22     char country_name[INITIAL_SIZE];
  23     country_name[INITIAL_SIZE - 1] = '\0';
  24 
  25     size_t i, j;
  26     part_t part;
  27         
  28     buff = (char *)malloc(INITIAL_SIZE * sizeof(char));
  29     
  30     if((fp = fopen(COUNTRY_CODES_FILE_NAME, "r")) == NULL) {
  31         free(buff);
  32         return ERROR_LOADING_COUNTRY_CODES;
  33     }
  34 
  35     while(fgets(buff, INITIAL_SIZE, fp) != NULL) {
  36         clean(country_name, INITIAL_SIZE);
  37         for(i = 0, j = 0, part = CODE; buff[i] != '\0'; i++) {
  38             if(buff[i] == ',') {
  39                 part = NAME;
  40                 i++;
  41             } else if (buff[i] == '\n') {
  42                 part = CODE;
  43                 j = 0;
  44             }
  45 
  46             switch(part)
  47             {
  48                 case CODE: buff2[i] = *(buff + i); break;
  49                 case NAME: country_name[j] = *(buff + i); j++; break;
  50             }
  51         }
  52         country_code = atoi(buff2);
  53         clean(buff2, INITIAL_SIZE);
  54         strcpy(country_codes[country_code], country_name);
  55     }
  56 
  57 //    Cierra el archivo que contiene el codigo de los paises de acuerdo al estandar;
  58     fclose(fp);
  59     free(buff);
  60     return OK;
  61 }
  62 
  63 
  64 status_t clean (char *buffer, size_t size)
  65 {
  66     size_t i;
  67     i = 0;
  68 
  69     if(buffer == NULL)
  70         return ERROR_NULL_POINTER;
  71 
  72     while(i < size) {
  73         buffer[i] = '\0';
  74         i++;
  75     }
  76     return OK;
  77 }
  78 
  79 //    Inicializa el arreglo alocando el caracter '\0' en todas las posiciones;
  80 status_t empty_country_codes(char **country_codes) 
  81 {
  82     size_t i, j;
  83     for(i = 0; i < COUNTRIES_NUMBER; i++)
  84         for(j = 0; j < (ARRAYS_LENGTH - 1); j++) {
  85             country_codes[i][j] = 'a';
  86         
  87         country_codes[i][ARRAYS_LENGTH - 1] = '\n';
  88         }
  89 
  90     return OK;
  91 }