util.c

Go to the documentation of this file.
00001 #include <stdlib.h>
00002 #include <stdio.h>
00003 #include <stdarg.h>
00004 #include <math.h>
00005 #include <string.h>
00006 
00007 #include "util.h"
00008 
00009 /**
00010  * \file util.c Algumas funções utilizadas no programa.
00011  */
00012 
00013 /// Mensagens de erro
00014 //#ifndef _QUIET  
00015 static const char *errmsgs[] = {   
00016   /* E_NONE        0 */  "sem erro\n",
00017   /* E_NOMEM      -1 */  "memoria insuficiente\n",
00018   /* E_FOPEN      -2 */  "não consegue abrir arquivo '%s'\n",
00019   /* E_FREAD      -3 */  "erro de leitura no arquivo '%s'\n",
00020   /* E_FWRITE     -4 */  "erro de escrita no arquivo '%s'\n",
00021   /* E_OPTION     -5 */  "opcao desconhecida -%c\n",
00022   /* E_OPTARG     -6 */  "opcao de argumento invalida -'%s'\n",
00023   /* E_FINEXIST   -7 */  "arquivo de entrada inexistente\n",
00024   /* E_UNKNOWN    -8 */  "erro desconhecido '%s'\n",
00025   /* E_NOTFOUND   -9 */  "elemento não encontrado\n",
00026   /* E_PARSEFAIL -10 */  "parsing problems: '%s'\n"
00027 };
00028 //#endif
00029 
00030 /// Nome deste programa. Aponta para argv[0] e é usado na função error() de 
00031 /// util.c
00032 //char *prgname;
00033 
00034 //-----------------------------------------------------------------------------
00035 /// Imprime um erro.
00036 //-----------------------------------------------------------------------------
00037 void error (int code, ...) {                          
00038 //#ifndef _QUIET 
00039         va_list    args;   
00040         const char *msg;  
00041 //#endif  
00042 
00043         if ((code > 0) || (code < E_UNKNOWN)) code = E_UNKNOWN;
00044 
00045 //#ifndef _QUIET                
00046         msg = errmsgs[-code];     
00047 //      fprintf(stderr, "\n%s: ", prgname);
00048         va_start(args, code);         
00049         vfprintf(stderr, msg, args); 
00050         va_end(args);                
00051 //#endif 
00052         exit(code);
00053 }
00054 
00055 /// Tamanho atual do buffer usado para ler uma linha.
00056 int actual_line_size = 80;
00057 
00058 /// Define qual implementação da função rad_line() será usada.
00059 ///     \sa read_line()
00060 #define READ_LINE1
00061 
00062 //-----------------------------------------------------------------------------
00063 /** Le uma linha. Possui 2 implementações:
00064 STR_HASH_CODE1: Implementação original: utiliza getc(), gastando muito processamento.
00065 STR_HASH_CODE2: Utiliza fgets, gastando muito (~10x) menos processamento.
00066 */
00067 //-----------------------------------------------------------------------------
00068 char *read_line(FILE *file) {
00069         char *line;
00070 #ifdef READ_LINE1
00071         register int index;
00072         register int ch;
00073 
00074         if (file == NULL) return NULL;
00075 
00076         line = (char*)calloc(actual_line_size,sizeof(char));
00077         if (line == NULL) error(E_NOMEM);
00078         index = 0;
00079         while (((ch=getc(file)) != '\n') && !feof(file)) {
00080                 line[index] = ch;
00081                 index++;
00082                 if (index >= actual_line_size) {
00083                         actual_line_size += (actual_line_size * 2) / 3;
00084                         line = (char*)realloc(line, actual_line_size*sizeof(char));
00085                         if (line == NULL) error(E_NOMEM);
00086                 }
00087         }
00088         line[index] = '\0';
00089 
00090         if (feof(file) && strlen(line) == 0) {
00091                 free(line);
00092                 line = NULL;
00093         }
00094 #endif
00095 #ifdef READ_LINE2
00096         int lineLen;
00097 
00098         if (file == NULL) return NULL;
00099 
00100         line = (char*)malloc(actual_line_size*sizeof(char));
00101         if (line == NULL) error(E_NOMEM);
00102 
00103         line[0] = 0;
00104         line[actual_line_size-2] = 0;
00105         fgets(line, actual_line_size*sizeof(char), file);
00106         
00107         // Se o penúltima for:
00108         // \0: leu a linha inteira (próximo obrigatoriamente é \0)
00109         // \n: foi a conta
00110         // outro: tem que ler mais
00111         while ( (line[actual_line_size-2]!='\0') && (line[actual_line_size-2]!='\n') ) {
00112                 int read = actual_line_size-1;
00113 
00114                 actual_line_size += (actual_line_size * 2) / 3;
00115                 line = (char*)realloc(line, actual_line_size*sizeof(char));
00116                 if (line == NULL) error(E_NOMEM);
00117                 //line[actual_line_size-2] = 0;
00118 
00119                 fgets(line+read, (actual_line_size-read)*sizeof(char), file);
00120         }
00121         lineLen = strlen(line);
00122         if (lineLen > 0) {
00123                 line[strlen(line)-1] = '\0';
00124         } else {
00125                 if (feof(file)) {
00126                         free(line);
00127                         line = NULL;
00128                 }
00129         }
00130 #endif
00131         
00132         return line;
00133 }
00134 
00135 //-----------------------------------------------------------------------------
00136 /// Retorna um string com a diferença de tempo entre 2 structs timeval.
00137 //-----------------------------------------------------------------------------
00138 char* elapsed_time(struct timeval tbegin, struct timeval tend) {
00139         long seg, mseg;
00140         char *time_str = (char*)malloc(80*sizeof(char));
00141         if (time_str == NULL) error(E_NOMEM);
00142         
00143         seg = tend.tv_sec-tbegin.tv_sec;
00144         mseg = tend.tv_usec-tbegin.tv_usec;
00145         if (mseg < 0) { 
00146                 seg--; 
00147                 mseg+=1000000;
00148         }
00149         if (mseg >= 1000000) {
00150                 seg += mseg/1000000;
00151                 mseg = mseg%1000000;
00152         }
00153         
00154         sprintf(time_str, "%ld.%.6ld s", seg, mseg);
00155         return time_str;
00156 }

Generated on Tue Jan 17 19:18:39 2006 for Void by  doxygen 1.4.6