📄 utils.c
字号:
/* Contents: Functions that may be of general use. Author: Markus Hagenbuchner Comments and questions concerning this program package may be sent to 'markus@artificial-neural.net' Changelog: 10/10/2006: - Corrected some source code comments. - Bug fix in SlideIn(): print correctly if not at beginning of a line *//************//* Includes *//************/#include <ctype.h>#include <math.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#include <unistd.h>#include "utils.h"/* Begin functions... *//* Memory management utilities *//*****************************************************************************Description: A fail save version of malloc. MyMalloc allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared. The function aborts immediately with an error message if the memory could not be allocated.Return value: A pointer to the allocated memory.Comment: Linux and some other operating systems do not immediately allocate the physical memory unless it is written to. Thus, malloc may not fail in the event that unsufficient memory is available, but any accesses to the memory at a later stage may fail. As a general rule of thumb, it is best to use calloc instead.*****************************************************************************/void *MyMalloc(size_t size){ void *ptr; if ((ptr = malloc(size)) == NULL){ fprintf(stderr, "\nOut of memory while trying to allocate %d bytes\n", (int)size); exit(0); } return ptr;}/*****************************************************************************Description: A fail save version of calloc. MyCalloc allocates memory for an array of nmemb elements of size and returns a pointer to the allocated memory. The memory is set to zero. The function aborts immediately with an error message if the memory could not be allocated.Return value: A pointer to the allocated memory.*****************************************************************************/void *MyCalloc(size_t nmemb, size_t size){ void *ptr; if ((ptr = calloc(nmemb, size)) == NULL){ fprintf(stderr, "\nError: Out of memory while trying to allocate %ld bytes\n", (long)size*(long)nmemb); exit(0); } return ptr;}/*****************************************************************************Description: A fail save version of realloc.Return value: A pointer to the allocated memory.*****************************************************************************/void *MyRealloc(void *ptr, size_t size){ void *newarray; if ((newarray = realloc(ptr, size)) == NULL){ fprintf(stderr, "Can't re-allocate %ld bytes of memory.\n", (long)size); return NULL; } return newarray;}/*****************************************************************************Description: Duplicate a memory area. This is similar to strndup but works on binary content.Return value: A pointer to the duplicated memory area.*****************************************************************************/void *memdup(void *ptr, size_t size){ void *dest; dest = MyMalloc(size); return memcpy(dest, ptr, size);}/* String functions *//*****************************************************************************Description: Concatenates the two strings str1 and str2. The result is stored in a new array for which sufficient memory is allocated.Return value: A pointer to an array which holds the concatenated strings.*****************************************************************************/char *stradd(char *str1, char *str2){ char *buffer = NULL; if (str1 == NULL){ if (str2 == NULL) return NULL; /* Return NULL if both strings are NULL */ else return strdup(str2); /* Return a copy of str2 if str1 is NULL */ } if (str2 == NULL) return strdup(str1); /* Return a copy of str1 if str2 is NULL */ /* allocate memory for concatenated string */ buffer = MyMalloc(strlen(str1) + strlen(str2) + 1); strcpy(buffer, str1); /* Copy str1 into the buffer */ strcat(buffer, str2); /* then concatenate str2 to the buffer */ return buffer; /* Return a pointer to the buffer */}/*****************************************************************************Description: Return a pointer pointing to the end of str. If str is an empty string or if str is a NULL pointer, then the returned pointer is the same as str. Otherwise, the pointer to the first occurence of the end_of_string marker ('\0') is returned.Return value: A pointer to the end of str.*****************************************************************************/char *strend(char *str){ if (str == NULL) return NULL; else return &str[strlen(str)];}/*****************************************************************************Description: Return pointer to first occurence of a character in str that is not a white space.Return value: A pointer to the first occurence of a character in str that is not a white space, or '\0' if str contains only white spaces.*****************************************************************************/char *strnspc(char *str){ if (str == NULL) return NULL; while (*str != '\0' && isspace((int)*str)) str++; return str;}/****************************************************************************Description: The strnstr() function finds the first occurrence of characters not found in substring needle in the string haystack. The terminating '\0' characters are not compared.Return value: The strnstr() function returns a pointer to the beginning of the substring, or NULL if the substring is not found.****************************************************************************/char *strnstr(char *haystack, char *needle){ char *cptr; if (haystack == NULL)/* Nothing to do and nothing to find, so return NULL */ return NULL; if (needle == NULL) /* No needle, so all characters in haystack match */ return haystack; for (;*haystack != '\0'; haystack++){ for (cptr = needle; *cptr != '\0'; cptr++){ if (*haystack == *cptr) break; } if (*cptr == '\0') /* No character in needle matched */ return haystack; } return NULL; /* all of haystack consists of characters in needle */}/*****************************************************************************Description: Same as atoi but returns a default value if the initial portion of the string pointed to by cptr does not hold an integer value. Return value: The converted value.*****************************************************************************/int oatoi(char *cptr, int idefault){ if (cptr == NULL || !(isdigit((int)*cptr) || *cptr == '+' || *cptr == '-')) return idefault; else return atoi(cptr);}/*****************************************************************************Description: Same as atoi but returns a unsigned falue or a default value if the initial portion of the string pointed to by cptr does not hold an unsigned value. Return value: The converted value.*****************************************************************************/unsigned oatou(char *cptr, int udefault){ if (cptr == NULL || !(isdigit((int)*cptr) || *cptr == '+')) return udefault; else return (unsigned)atoi(cptr);}/*****************************************************************************Description: Same as atof but returns a default value if the initial portion of the string pointed to by cptr does not hold a float value.Return value: The converted value.*****************************************************************************/float oatof(char *cptr, float fdefault){ if (cptr == NULL || !(isdigit((int)*cptr) || *cptr == '+' || *cptr == '-' || *cptr == '.')) return fdefault; else return (float)atof(cptr);}/*****************************************************************************Description: Same as atoi but stores the integer in ival. ival remains unchnaged if cptr does not start with integer information. Return value: 1 if conversion succussful, 0 otherwise*****************************************************************************/int satoi(char *cptr, int *ival){ if (cptr == NULL || !(isdigit((int)*cptr) || *cptr == '+' || *cptr == '-')) return 0; *ival = atoi(cptr); return 1;}/*****************************************************************************Description: Converts the initial portion of the string pointed to by cptr to unsigned and stores the value in uval. uval remains unchanged if cptr does not start with unsigned information. Return value: 1 if conversion succussful, 0 otherwise*****************************************************************************/int satou(char *cptr, unsigned *uval){ if (cptr == NULL || !(isdigit((int)*cptr) || *cptr == '+')) return 0; *uval = (unsigned)atoi(cptr); return 1;}/*****************************************************************************Description: Same as atof but stores the float in fval. fval remains unchanged if cptr does not start with float information.Return value: 1 if conversion succussful, 0 otherwise*****************************************************************************/int satof(char *cptr, float *fval){ if (cptr == NULL || !(isdigit((int)*cptr) || *cptr == '+' || *cptr == '-' || *cptr == '.')) return 0; *fval = (float)atof(cptr); return 1;}/*****************************************************************************Description: Same as atof but stores a string in sptr. sptr remains unchanged if cptr is NULL or an empty string.Return value: 1 if conversion succussful, 0 otherwise*****************************************************************************/int satos(char *cptr, char **sptr){ if (cptr == NULL || *cptr == '\0') return 0; *sptr = strdup(cptr); return 1;}/*****************************************************************************Description: Check whether a given string str starts with a substring sub. This is the same as strncmp(sub, str, strlen(sub)).Return value: length of sub if str starts with sub, or -1 else*****************************************************************************/int strstart(char *sub, char *str){ int len; len = strlen(sub); if (len == 0 || !strncmp(sub, str, len)) return len; else return -1;}/* Print functions *//*****************************************************************************Description: Write text to ostream and flush the output immediately.Return value: fprint returns the number of characters printed.*****************************************************************************/int fprint(FILE *ostream, char *text){ int res; res = fprintf(ostream, text); fflush(ostream); return res;}/*****************************************************************************Description: Prints a message by sliding the message in from the left at a given speedReturn value: This function does not return a value.*****************************************************************************/void SlideIn(FILE *ostream, int speed, char *msg){ int i, j, len; /* Sanity check */ if (msg == NULL) return; len = strlen(msg); for (i = 1; i <= len; i++){ fprintf(ostream, "%s", &msg[len-i]); usleep(speed * 10000); for (j = 0; j < i; j++) fputc('\b', ostream); }}/*****************************************************************************Description: High precision print of a float f to an output stream ofile.Return value: fprint does not return a value.*****************************************************************************/void PrintFloat(FILE *ofile, float f){ if (f < 0.0){ /* If the value is negative */ fputc('-', ofile); /* print the sign, and */ f = -f; /* make it a positive value */ } fprintf(ofile, "%d.", (int)f);/* Print the integer component of the value */ do{ f = f-((int)f); /* Substract the integer value from the value */ f = f*10.0; /* Obtain the next decimal value */ fprintf(ofile, "%d", (int)f); /* and print it. */ }while(f>0.0); /* while the value has decimals to print */}/*****************************************************************************Description: Convert a given number of seconds into minutes, hours, days into a static buffer.Return value: Pointer to the buffer containing the time as a string.*****************************************************************************/char *PrintTime(time_t time){ static char buffer[32]; buffer[0] = '\0'; if (time/86400 > 0){ sprintf(buffer, "%2ddays", (int)time/86400);/* number of days */ time = time % 86400; } if (time / 3600 > 0){ sprintf(strend(buffer), " %2dhrs", (int)time/3600); /* number of hours */ time = time % 3600; } if (time / 60 > 0){ sprintf(strend(buffer), " %2dmins", (int)time/60); /* number of minutes */ time = time % 60; } if (time > 0) sprintf(strend(buffer), " %2dsecs", (int)time); /* number of seconds */ if (time == 0L) sprintf(buffer, " 0secs"); /* Treat 0 seconds as a special case */ return buffer;}/* Functions that help to deal with command line options */#define TYPE_STRING 1#define TYPE_INT 2#define TYPE_UNSIGNED 3#define TYPE_FLOAT 4/*****************************************************************************Description: Retrieve the value of a command line parameter. Some error checking is performed to ensure the type of the value is correct.Return value: The function does not return a value.*****************************************************************************/void GetArg(int type, int argc, char **argv, int idx, void *dest){
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -