Esempio n. 1
0
char		*my_get_next_line(int fd)
{
  static char	*buffer;
  char		*line;
  int		i;

  if ((buffer == NULL && (buffer = my_read_dup(fd, SREAD)) == NULL)
      || (i = my_check_line(BLANK, buffer)) < 0 || fd < 0)
    return (NULL);
  while (i != 1)
    {
      if ((line = my_strdup(buffer)) == NULL
	  || (i == 0 && (buffer = my_readline(fd, buffer, SREAD)) == NULL)
	  || (i = my_check_line(line, buffer)) < 0)
	return (NULL);
      if (i == 0 && my_strcmp(buffer, line) == 0)
	{
	  free(buffer);
	  return (NULL);
	}
      free(line);
    }
  if ((line = my_get_line(buffer)) == NULL
      || (buffer = my_cut_line(buffer)) == NULL
      || (i = my_strlen(buffer)) < 0)
    return (NULL);
  return (line);
}
Esempio n. 2
0
// Main---------------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[]) {

    int repeat, aux;
    char *input;

    // A lista schema é criada e lida da stdin
    SCHEMA *schema = create_schema();
    get_schema(schema);

    do {
        // A cada repeticao le um comando da stdin
        repeat = 1;
        input = my_get_line(stdin, &aux);
        if(input == NULL) fprintf(stderr, "chamada errada\n");

        // Analisa qual o comando desejado e chama a(s) funcao(oes) responsavel(is) por realiza-lo
        if(strcmp(input, "dump_schema") == 0) {
            dump_schema(schema);
        } else if(strcmp(input, "dump_data") == 0) {
            dump_data(schema);
        } else if(strcmp(input, "dump_index") == 0) {
            print_index(schema);
        } else if(strcmp(input, "update_index") == 0) {
            get_index(schema);
            sort_index(schema);
        } else if(strcmp(input, "insert") == 0) {
            insert_data(schema);
        } else if(strcmp(input, "select") == 0) {
            search_index_data(schema);
        } else if(strcmp(input, "exit") == 0) {
            // Caso seja digitado "exit", repeat recebe 0, saindo do loop
            repeat = 0;
        }

        // A cada repeticao input eh liberado caso tenha sido alocado adequadamente
        if(input != NULL) free(input);
    } while(repeat);

    // Libera a memoria alocada
    delete_schema(&schema);

    return 0;
}
Esempio n. 3
0
/* return 0 on everything-is-fine, and non-zero otherwise */
int parseconfig(const char *filename, struct GlobalConfig *global)
{
  FILE *file;
  char filebuffer[512];
  bool usedarg = FALSE;
  int rc = 0;
  struct OperationConfig *operation = global->first;

  if(!filename || !*filename) {
    /* NULL or no file name attempts to load .curlrc from the homedir! */

#ifndef __AMIGA__
    char *home = homedir();    /* portable homedir finder */
    filename = CURLRC;   /* sensible default */
    if(home) {
      if(strlen(home) < (sizeof(filebuffer) - strlen(CURLRC))) {
        msnprintf(filebuffer, sizeof(filebuffer),
                  "%s%s%s", home, DIR_CHAR, CURLRC);

#ifdef WIN32
        /* Check if the file exists - if not, try CURLRC in the same
         * directory as our executable
         */
        file = fopen(filebuffer, FOPEN_READTEXT);
        if(file != NULL) {
          fclose(file);
          filename = filebuffer;
        }
        else {
          /* Get the filename of our executable. GetModuleFileName is
           * already declared via inclusions done in setup header file.
           * We assume that we are using the ASCII version here.
           */
          int n = GetModuleFileNameA(0, filebuffer, sizeof(filebuffer));
          if(n > 0 && n < (int)sizeof(filebuffer)) {
            /* We got a valid filename - get the directory part */
            char *lastdirchar = strrchr(filebuffer, '\\');
            if(lastdirchar) {
              size_t remaining;
              *lastdirchar = 0;
              /* If we have enough space, build the RC filename */
              remaining = sizeof(filebuffer) - strlen(filebuffer);
              if(strlen(CURLRC) < remaining - 1) {
                msnprintf(lastdirchar, remaining,
                          "%s%s", DIR_CHAR, CURLRC);
                /* Don't bother checking if it exists - we do that later */
                filename = filebuffer;
              }
            }
          }
        }
#else /* WIN32 */
        filename = filebuffer;
#endif /* WIN32 */
      }
      Curl_safefree(home); /* we've used it, now free it */
    }

# else /* __AMIGA__ */
    /* On AmigaOS all the config files are into env:
     */
    filename = "ENV:" CURLRC;

#endif
  }

  if(strcmp(filename, "-"))
    file = fopen(filename, FOPEN_READTEXT);
  else
    file = stdin;

  if(file) {
    char *line;
    char *aline;
    char *option;
    char *param;
    int lineno = 0;
    bool dashed_option;

    while(NULL != (aline = my_get_line(file))) {
      int res;
      bool alloced_param = FALSE;
      lineno++;
      line = aline;

      /* line with # in the first non-blank column is a comment! */
      while(*line && ISSPACE(*line))
        line++;

      switch(*line) {
      case '#':
      case '/':
      case '\r':
      case '\n':
      case '*':
      case '\0':
        Curl_safefree(aline);
        continue;
      }

      /* the option keywords starts here */
      option = line;

      /* the option starts with a dash? */
      dashed_option = option[0]=='-'?TRUE:FALSE;

      while(*line && !ISSPACE(*line) && !ISSEP(*line, dashed_option))
        line++;
      /* ... and has ended here */

      if(*line)
        *line++ = '\0'; /* zero terminate, we have a local copy of the data */

#ifdef DEBUG_CONFIG
      fprintf(stderr, "GOT: %s\n", option);
#endif

      /* pass spaces and separator(s) */
      while(*line && (ISSPACE(*line) || ISSEP(*line, dashed_option)))
        line++;

      /* the parameter starts here (unless quoted) */
      if(*line == '\"') {
        /* quoted parameter, do the quote dance */
        line++;
        param = malloc(strlen(line) + 1); /* parameter */
        if(!param) {
          /* out of memory */
          Curl_safefree(aline);
          rc = 1;
          break;
        }
        alloced_param = TRUE;
        (void)unslashquote(line, param);
      }
      else {
        param = line; /* parameter starts here */
        while(*line && !ISSPACE(*line))
          line++;

        if(*line) {
          *line = '\0'; /* zero terminate */

          /* to detect mistakes better, see if there's data following */
          line++;
          /* pass all spaces */
          while(*line && ISSPACE(*line))
            line++;

          switch(*line) {
          case '\0':
          case '\r':
          case '\n':
          case '#': /* comment */
            break;
          default:
            warnf(operation->global, "%s:%d: warning: '%s' uses unquoted "
                  "white space in the line that may cause side-effects!\n",
                  filename, lineno, option);
          }
        }
        if(!*param)
          /* do this so getparameter can check for required parameters.
             Otherwise it always thinks there's a parameter. */
          param = NULL;
      }

#ifdef DEBUG_CONFIG
      fprintf(stderr, "PARAM: \"%s\"\n",(param ? param : "(null)"));
#endif
      res = getparameter(option, param, &usedarg, global, operation);

      if(!res && param && *param && !usedarg)
        /* we passed in a parameter that wasn't used! */
        res = PARAM_GOT_EXTRA_PARAMETER;

      if(res == PARAM_NEXT_OPERATION) {
        if(operation->url_list && operation->url_list->url) {
          /* Allocate the next config */
          operation->next = malloc(sizeof(struct OperationConfig));
          if(operation->next) {
            /* Initialise the newly created config */
            config_init(operation->next);

            /* Copy the easy handle */
            operation->next->easy = global->easy;

            /* Set the global config pointer */
            operation->next->global = global;

            /* Update the last operation pointer */
            global->last = operation->next;

            /* Move onto the new config */
            operation->next->prev = operation;
            operation = operation->next;
          }
          else
            res = PARAM_NO_MEM;
        }
      }

      if(res != PARAM_OK && res != PARAM_NEXT_OPERATION) {
        /* the help request isn't really an error */
        if(!strcmp(filename, "-")) {
          filename = "<stdin>";
        }
        if(res != PARAM_HELP_REQUESTED &&
           res != PARAM_MANUAL_REQUESTED &&
           res != PARAM_VERSION_INFO_REQUESTED &&
           res != PARAM_ENGINES_REQUESTED) {
          const char *reason = param2text(res);
          warnf(operation->global, "%s:%d: warning: '%s' %s\n",
                filename, lineno, option, reason);
        }
      }

      if(alloced_param)
        Curl_safefree(param);

      Curl_safefree(aline);
    }
    if(file != stdin)
      fclose(file);
  }
  else
    rc = 1; /* couldn't open the file */

  return rc;
}
Esempio n. 4
0
void search_index_data(SCHEMA *schema) {

    int i, test_count, search_return, n_elements;
    long int location, offset;
    void *aux;
    char *filename_index, *search_term, *filename_data, *print_field, *search_key;
    NODE *node = schema->sentry;
    FILE *fp_index, *fp_data;

    // Sao lidos da stdin o campo a ser analisado na busca, a chave desejada e o campo a ser impresso apos a busca
    search_term = my_get_line(stdin, &i);
    search_key = my_get_line(stdin, &i);
    print_field = my_get_line(stdin, &i);

    // test_count armazena o numero de iteracoes de busca e offset armazena o offset do tipo sendo analisado em relação á posição do elemento
    // como um todo
    test_count = 0;
    offset = 0;
    // Sao analizados todos os elementos ate ser encontrado o que deseja-se para a busca
    for(i = 0; i < schema->n_elements; i++) {
        node = node->next;
        if(strcmp(search_term, node->name) == 0 && node->order) {

            // O arquivo .idx é aberto para leitura
            filename_index = (char*)malloc(sizeof(char) * (strlen(schema->name) + 6 + strlen(node->name)));
            strcpy(filename_index, schema->name);
            strcat(filename_index, "-");
            strcat(filename_index, node->name);
            strcat(filename_index, ".idx");
            fp_index = fopen(filename_index, "rb");

            if(fp_index != NULL) {

                // Analisa-se quantos elementos estão presentes no  .idx
                fseek(fp_index, 0, SEEK_END);
                location = ftell(fp_index);
                n_elements = (int)(location/(sizeof(long int) + node->size));
                fseek(fp_index, 0, SEEK_SET);

                // É realizada a busca binaria
                search_return = binary_search(fp_index, schema, node, search_key, 0, n_elements-1, &test_count);
                // E o arquivo é fechado
                fclose(fp_index);
                if(search_return == -1) {
                    // Caso não tenha sido encontrado o item desejado no indice, realiza-se a busca sequencial
                    // nos itens que foram adicionados no fim do .data
                    search_return = sequential_search(schema, node, search_key, &test_count, offset);
                }
            } else {
                fprintf(stderr, "could not open file\n");
                exit(1);
            }
            // Liberacao da memoria alocada
            free(filename_index);

            // Imprime o numero de iteracoes da busca realizadas
            printf("%d\n", test_count);
            // Caso nao tenha sido encontrado o item, imprime a mensagem de erro
            if(search_return == -1) {
                printf("value not found\n");
            } else {
                // Caso o item tenha sido encontrado, procura o offset do item a ser impresso em relação
                // ao elemento como um todo
                node = schema->sentry;
                offset = 0;
                for(i = 0; i < schema->n_elements; i++) {
                    node = node->next;
                    if(strcmp(print_field, node->name) == 0) {
                        break;
                    }
                    offset += node->size;
                }

                // O arquivo .data é aberto para leitura
                filename_data = (char*)malloc(sizeof(char) * (strlen(schema->name)+6));
                strcpy(filename_data, schema->name);
                strcat(filename_data, ".data");
                fp_data = fopen(filename_data, "rb");
                if(fp_data == NULL) {
                    fprintf(stderr, "could not open file\n");
                    exit(1);
                }

                // A variavel aux armazena o conteudo do item a ser impresso
                fseek(fp_data, search_return+offset, SEEK_SET);
                aux = malloc(node->size);
                fread(aux, node->size, 1, fp_data);
                // E o arquivo é fechado
                fclose(fp_data);

                // A impressao é feita de acordo com o tipo sendo analisado
                if(node->id == INT_T) {
                    printf("%d\n", *((int*)aux));
                } else if(node->id == DOUBLE_T) {
                    printf("%.2lf\n", *((double*)aux));
                } else if(node->id == STRING_T) {
                    printf("%s\n", (char*)aux);
                }
                // E a memoria alocada é liberada
                free(aux);
                free(filename_data);
            }
            // caso o item seja encontrado, o valor de i é alterado para que saia do loop
            i = schema->n_elements+1;
        }
        // O valor de offset é incrementado com o tamanho do item anterior analisado
        if(i <= schema->n_elements) {
            offset += node->size;
        }
    }

    // Caso não tenha sido realizada nenhuma iteracao de busca, não foi encontrado nenhum arquivo .idx do campo buscado
    if(test_count == 0) {
        printf("index not found\n");
    }
    // Libera a memoria alocada
    free(search_term);
    free(search_key);
    free(print_field);
}
Esempio n. 5
0
/* return 0 on everything-is-fine, and non-zero otherwise */
int parseconfig(const char *filename,
                struct Configurable *config)
{
  int res;
  FILE *file;
  char filebuffer[512];
  bool usedarg;
  char *home;
  int rc = 0;

  if(!filename || !*filename) {
    /* NULL or no file name attempts to load .curlrc from the homedir! */

#ifndef __AMIGA__
    filename = CURLRC;   /* sensible default */
    home = homedir();    /* portable homedir finder */
    if(home) {
      if(strlen(home) < (sizeof(filebuffer) - strlen(CURLRC))) {
        snprintf(filebuffer, sizeof(filebuffer),
                 "%s%s%s", home, DIR_CHAR, CURLRC);

#ifdef WIN32
        /* Check if the file exists - if not, try CURLRC in the same
         * directory as our executable
         */
        file = fopen(filebuffer, "r");
        if(file != NULL) {
          fclose(file);
          filename = filebuffer;
        }
        else {
          /* Get the filename of our executable. GetModuleFileName is
           * already declared via inclusions done in setup header file.
           * We assume that we are using the ASCII version here.
           */
          int n = GetModuleFileName(0, filebuffer, sizeof(filebuffer));
          if(n > 0 && n < (int)sizeof(filebuffer)) {
            /* We got a valid filename - get the directory part */
            char *lastdirchar = strrchr(filebuffer, '\\');
            if(lastdirchar) {
              size_t remaining;
              *lastdirchar = 0;
              /* If we have enough space, build the RC filename */
              remaining = sizeof(filebuffer) - strlen(filebuffer);
              if(strlen(CURLRC) < remaining - 1) {
                snprintf(lastdirchar, remaining,
                         "%s%s", DIR_CHAR, CURLRC);
                /* Don't bother checking if it exists - we do
                 * that later
                 */
                filename = filebuffer;
              }
            }
          }
        }
#else /* WIN32 */
        filename = filebuffer;
#endif /* WIN32 */
      }
      Curl_safefree(home); /* we've used it, now free it */
    }

# else /* __AMIGA__ */
    /* On AmigaOS all the config files are into env:
     */
    filename = "ENV:" CURLRC;

#endif
  }

  if(strcmp(filename,"-"))
    file = fopen(filename, "r");
  else
    file = stdin;

  if(file) {
    char *line;
    char *aline;
    char *option;
    char *param;
    int lineno = 0;
    bool alloced_param;

    while(NULL != (aline = my_get_line(file))) {
      lineno++;
      line = aline;
      alloced_param=FALSE;

      /* line with # in the first non-blank column is a comment! */
      while(*line && ISSPACE(*line))
        line++;

      switch(*line) {
      case '#':
      case '/':
      case '\r':
      case '\n':
      case '*':
      case '\0':
        Curl_safefree(aline);
        continue;
      }

      /* the option keywords starts here */
      option = line;
      while(*line && !ISSPACE(*line) && !ISSEP(*line))
        line++;
      /* ... and has ended here */

      if(*line)
        *line++ = '\0'; /* zero terminate, we have a local copy of the data */

#ifdef DEBUG_CONFIG
      fprintf(stderr, "GOT: %s\n", option);
#endif

      /* pass spaces and separator(s) */
      while(*line && (ISSPACE(*line) || ISSEP(*line)))
        line++;

      /* the parameter starts here (unless quoted) */
      if(*line == '\"') {
        /* quoted parameter, do the quote dance */
        line++;
        param = malloc(strlen(line) + 1); /* parameter */
        if(!param) {
          /* out of memory */
          Curl_safefree(aline);
          rc = 1;
          break;
        }
        alloced_param = TRUE;
        (void)unslashquote(line, param);
      }
      else {
        param = line; /* parameter starts here */
        while(*line && !ISSPACE(*line))
          line++;
        *line = '\0'; /* zero terminate */
      }

      if(param && !*param) {
        /* do this so getparameter can check for required parameters.
           Otherwise it always thinks there's a parameter. */
        if(alloced_param)
          Curl_safefree(param);
        param = NULL;
      }

#ifdef DEBUG_CONFIG
      fprintf(stderr, "PARAM: \"%s\"\n",(param ? param : "(null)"));
#endif
      res = getparameter(option, param, &usedarg, config);

      if(param && *param && !usedarg)
        /* we passed in a parameter that wasn't used! */
        res = PARAM_GOT_EXTRA_PARAMETER;

      if(res != PARAM_OK) {
        /* the help request isn't really an error */
        if(!strcmp(filename, "-")) {
          filename = (char *)"<stdin>";
        }
        if(PARAM_HELP_REQUESTED != res) {
          const char *reason = param2text(res);
          warnf(config, "%s:%d: warning: '%s' %s\n",
                filename, lineno, option, reason);
        }
      }

      if(alloced_param)
        Curl_safefree(param);

      Curl_safefree(aline);
    }
    if(file != stdin)
      fclose(file);
  }
  else
    rc = 1; /* couldn't open the file */

  return rc;
}