nsb

utils.c

nsb
Jul 14th, 2011
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <error.h>
  5. #include <errno.h>
  6. #include "utils.h"
  7.  
  8. /**
  9.  * Get memory space and check, wheter I have it
  10.  */
  11. void *
  12. xmalloc(size_t size){
  13.     void * pointer;
  14.     pointer = malloc(size);
  15.     errno = 0;
  16.     if(pointer == NULL){
  17.         error(0, 0, "Could not allocate enough space!");
  18.     }
  19.     if(errno){
  20.         error(0, errno, strerror(errno));
  21.     }
  22.     return pointer;
  23. }
  24.  
  25. /**
  26.  * reallocate space and check it
  27.  */
  28. void *
  29. xrealloc(void * pointer, size_t size){
  30.     pointer = realloc(pointer, size);
  31.     errno = 0;
  32.     if(pointer == NULL){
  33.         error(0, 0, "Could not reallocate space!");
  34.     }
  35.     if(errno){
  36.         error(0, errno, strerror(errno));
  37.     }
  38.     return pointer;
  39. }
  40.  
  41. /**
  42.  * safe version of strcat
  43.  */
  44. void
  45. cat(char **to, char * from){
  46.     char * buffer;
  47.     buffer = (char *) xmalloc (sizeof(char) * (strlen(*to) + 1));
  48.     cpy(&buffer, *to);
  49.     printf("buffer: %s\n", buffer); //DEBUG
  50.     int length = strlen(*to) + strlen(from) + 1;
  51.     *to = (char *) xrealloc(*to, length * sizeof(char));
  52.     cpy(to, buffer);
  53.     printf("to: %s\n", *to); //DEBUG
  54.     printf("from: %s\n", from); //DEBUG
  55.     errno = 0;
  56.     if(strcat(*to, from) != *to){
  57.         error(0, 0, "Could not concate the string %s\n", from);
  58.     }
  59.     if(errno){
  60.         error(0, errno, strerror(errno));
  61.     }
  62.     printf("to: %s\n", *to); //DEBUG
  63. }
  64.  
  65. /**
  66.  * safe version strcpy
  67.  */
  68. void
  69. cpy(char **to, char * from){
  70.     int length = strlen(from) + 1;
  71.     *to = (char *) xrealloc(*to, length * sizeof(char));
  72.     errno = 0;
  73.     if(strcpy(*to, from) != *to){
  74.         error(0, errno, "Could not cpy the string %s\n", from);
  75.     }
  76.     if(errno){
  77.         error(0, errno, strerror(errno));
  78.     }
  79. }
  80.  
  81. /**
  82.  * Add "/" to pathname
  83.  */
  84. void
  85. addslash(char * path){
  86.     //if(strcat(path, "/") != path){
  87.     //    fprintf(stderr, "ERROR: Could not add \"/\" to path %s!\n", path);
  88.     //    exit(1);
  89.     //}
  90.     cat(&path, "/");
  91. }
Advertisement
Add Comment
Please, Sign In to add comment