在这里,我还是希望对lib中的其他一些接口(工具函数)进行相关分析与介绍。
snprintf.h和snprintf.c文件(字符串格式化函数)
下面是两个文件的源代码:
/*snprintf.h --------------------------------------------------------*/ #ifndef HAVE_SNPRINTF #ifdef __cplusplus extern "C" { #endif int snprintf(char *buf, size_t size, const char *fmt, ...); #ifdef __cplusplus } /* end extern "C" */ #endif #endif /* HAVE_SNPRINTF */ #endif /* SNPRINTF_H */ /*snprintf.c ----------------------------------------------------------*/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef HAVE_SNPRINTF #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include "snprintf.h" #ifdef __cplusplus extern "C" { #endif int snprintf(char *buf, size_t size, const char *fmt, ...) { int n; va_list ap; va_start(ap, fmt); vsprintf(buf, fmt, ap); /* Sigh, some vsprintf's return ptr, not length */ n = strlen(buf); va_end(ap); if ( n >= size ) { printf( "snprintf: overflowed array\n" ); exit(1); } return(n); } #ifdef __cplusplus } /* end extern "C" */ #endif #endif /* HAVE_SNPRINTF */
首先,为什么要单独写一个snprintf函数,而不直接用sprintf函数?
sprintf函数简介:
sprintf:字符串格式化命令,主要功能是把格式化的数据写入某个字符串中。sprintf 是个变参函数。
buffer:char型指针,指向将要写入的字符串的缓冲区。
format:格式化字符串。
[argument]...:可选参数,可以是任何类型的数据。
返回值:字符串长度(strlen)
源代码作者在阐述自己的看法时认为,snprintf函数比sprintf函数更加安全一些,它可以检测溢出问题。
再则,我想对snprintf函数中的可选参数格式进行一些简要介绍:
当无法列出传递函数的所有实参的类型和数目时,C语言提出可用省略号指定参数表。如:
void foo(...); void foo(parm_list,...);
函数参数的传递原理:
函数参数是以数据结构中的栈的形式存取,从右至左依次入栈。
对于如何获取省略号表示的参数,这里采用va_list的方法:
VA_LIST 是在C语言中解决变参问题的一组宏,在<stdarg.h>头文件下。
va_list ap; //声明一个变量来转换参数列表 va_start(ap,fmt); //初始化变量 va_end(ap); //结束变量列表,和va_start成对使用
VA_LIST的用法:
(1)在函数里定义一具VA_LIST型的变量,这个变量是指向参数的指针;
(2)用VA_START宏初始化变量刚定义的VA_LIST变量,这个宏的第二个参数是第一个可变参数的前一个参数,是一个固定的参数(如在运行VA_START(ap,fmt)以后,ap指向第一个可变参数在堆栈的地址);
(3)用VA_ARG返回可变的参数,VA_ARG的第二个参数是你要返回的参数的类型,VA_ARG返回参数列表中的当前参数并使ap指向参数列表中的下一个参数;
(4)用VA_END宏结束可变参数的获取。然后你就可以在函数里使用第二个参数了。如果函数有多个可变参数的,依次调用VA_ARG获取各个参数。
对于sprintf,printf,以及vsprintf的区别,可以参考:http://blog.csdn.net/anye3000/article/details/6593551
那么,snprintf函数究竟是实现什么功能呢?一句话,将变量fmt准确地传递到buff缓冲区中。
gettimeofday.h和gettimeofday.c(时间获取函数)
下面是两个文件的源代码:
/*gettimeofday.h*/ #ifndef GETTIMEOFDAY_H #define GETTIMEOFDAY_H #ifndef HAVE_GETTIMEOFDAY #ifdef __cplusplus extern "C" { #endif int gettimeofday( struct timeval* tv, void* timezone ); #ifdef __cplusplus } /* end extern "C" */ #endif #endif /* HAVE_GETTIMEOFDAY */ #endif /* GETTIMEOFDAY_H */ /*gettimeofday.c*/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef HAVE_GETTIMEOFDAY #include "headers.h" #include "gettimeofday.h" #ifdef __cplusplus extern "C" { #endif int gettimeofday( struct timeval* tv, void* timezone ) { FILETIME time; double timed; GetSystemTimeAsFileTime( &time ); // Apparently Win32 has units of 1e-7 sec (tenths of microsecs) // 4294967296 is 2^32, to shift high word over // 11644473600 is the number of seconds between // the Win32 epoch 1601-Jan-01 and the Unix epoch 1970-Jan-01 // Tests found floating point to be 10x faster than 64bit int math. timed = ((time.dwHighDateTime * 4294967296e-7) - 11644473600.0) + (time.dwLowDateTime * 1e-7); tv->tv_sec = (long) timed; tv->tv_usec = (long) ((timed - tv->tv_sec) * 1e6); return 0; } #ifdef __cplusplus } /* end extern "C" */ #endif #endif /* HAVE_GETTIMEOFDAY */
在gettimeofday函数实现源代码中,用到了一个名为tv(timeval)的结构体,timeval结构体的定义(time.h)如下:
struct timeval { __time_t tv_sec; /* Seconds. */ __suseconds_t tv_usec; /* Microseconds. */ };
其中,tv_sec为"the Win32 epoch 1601-Jan-01 and the Unix epoch 1970-Jan-01"到创建struct timeval时的秒数,tv_usec为微秒数,即秒后面的零头。
gettimeofday()功能是得到当前时间和时区,分别写到tv和timezone中,如果timezone为NULL则不向timezone写入(显然上述源代码void *timezone为空)。
string.c和stdio.c:
这两个文件主要设置了相关字符处理函数,同时能各进行一些数据格式的转化(主要涉及到G-M-K等方面的转化)。
string.c :(内容见注释)
#include "headers.h" #include "util.h" #ifdef __cplusplus extern "C" { #endif /* ------------------------------------------------------------------- * pattern * * Initialize the buffer with a pattern of (index mod 10). * 按照给定的方法对一个缓冲区进行初始化工作 * 具体的初始化方式为:Buffer中的值为index%10,即buffer="0123456789......" * ------------------------------------------------------------------- */ void pattern( char *outBuf, int inBytes ) { assert( outBuf != NULL ); while ( inBytes-- > 0 ) { outBuf[ inBytes ] = (inBytes % 10) + '0'; } } /* end pattern */ /* ------------------------------------------------------------------- * replace( text, length, replacement ) * * replaces text[ 0..length-1 ] with replacement, shifting * text[ length.. ] so it is not lost in any way. * 代换(替代):将text的从0开始的length长度的字符串替换为replacement内容,text的length * 以上的内容通过移位不会丢失。 * ------------------------------------------------------------------- */ void replace( char *position, int poslen, const char *replacement ) { int orig_len = strlen( position ); int repl_len = strlen( replacement ); /* void *memmove( void* dest, const void* src, size_t count ); * memmove用于从src拷贝count个字符到dest,如果目标区域和源区域有重叠的话, * memmove能够保证源串在被覆盖之前将重叠区域的字节拷贝到目标区域中。但复制后 * src内容会被更改。但是当目标区域与源区域没有重叠则和memcpy函数功能相同。*/ /* move memory from (position + poslen) down to (position + repl_len). * remember the null terminating byte! */ memmove( position + repl_len, position + poslen, orig_len - poslen + 1 ); /* Put in replacement string */ memcpy( position, replacement, repl_len ); } /* ------------------------------------------------------------------- * concat( destination, length, source ) * * Similar to strcat, but will not overwrite the bounds of dest * and will *always* terminate dest (unlike strncat). * 与strcat函数比较相似,source和destination区域不能有重叠,实现的功能是将 * source接写到destination后,不过与strncat不一样的是,当接续到destination后, * 同时超出destination内存边界是,接续过程便会终结。 * ------------------------------------------------------------------- */ char *concat( char *dest, int len, const char *src ) { char *s = dest; char *end = dest + len; /* make s point to the end (terminating null) of s1 */ while ( *s != '\0' ) s++; /* copy characters until end (before terminating null) of src, * or end of dest buffer */ while ( *src != '\0' ) { *s++ = *src++; if ( s >= end ) { s--; /* back up one for terminating null */ break; } } /* null terminate */ *s = '\0'; return dest; } /* ------------------------------------------------------------------- * copy( destination, length, source ) * * Similar to strcpy, but will not overwrite the bounds of dest * and will *always* terminate dest (unlike strncpy). * 其内容与上述concat功能相似,只是此为复制,上面的为接续。 * ------------------------------------------------------------------- */ char *copy( char *dest, int len, const char *src ) { char *s = dest; char *end = dest + len; /* copy characters until end (before terminating null) of src, * or end of dest buffer */ while ( *src != '\0' ) { *s++ = *src++; if ( s >= end ) { s--; /* back up one for terminating null */ break; } } /* null terminate */ *s = '\0'; return dest; } #ifdef __cplusplus } /* end extern "C" */ #endif
stdio.c :(内容见注释)
#include "headers.h" #include "util.h" #ifdef __cplusplus extern "C" { #endif const long kKilo_to_Unit = 1024; const long kMega_to_Unit = 1024 * 1024; const long kGiga_to_Unit = 1024 * 1024 * 1024; const long kkilo_to_Unit = 1000; const long kmega_to_Unit = 1000 * 1000; const long kgiga_to_Unit = 1000 * 1000 * 1000; /* ------------------------------------------------------------------- * byte_atof * * Given a string of form #x where # is a number and x is a format * character listed below, this returns the interpreted float. * Gg, Mm, Kk are giga, mega, kilo respectively * byte_atof函数实现的是对形如3M的#x字符串进行分析,同时输出相应比例数值(double型) * ------------------------------------------------------------------- */ double byte_atof( const char *inString ) { double theNum; char suffix = '\0'; assert( inString != NULL ); /* scan the number and any suffices */ sscanf( inString, "%lf%c", &theNum, &suffix ); /* convert according to [Gg Mm Kk] */ switch ( suffix ) { case 'G': theNum *= kGiga_to_Unit; break; case 'M': theNum *= kMega_to_Unit; break; case 'K': theNum *= kKilo_to_Unit; break; case 'g': theNum *= kgiga_to_Unit; break; case 'm': theNum *= kmega_to_Unit; break; case 'k': theNum *= kkilo_to_Unit; break; default: break; } return theNum; } /* end byte_atof */ /* ------------------------------------------------------------------- * byte_atoi * * Given a string of form #x where # is a number and x is a format * character listed below, this returns the interpreted integer. * Gg, Mm, Kk are giga, mega, kilo respectively * byte_atof函数实现的是对形如3M的#x字符串进行分析,同时输出相应比例数值(int型) * ------------------------------------------------------------------- */ int byte_atoi( const char *inString ) { double theNum; char suffix = '\0'; assert( inString != NULL ); /* scan the number and any suffices */ sscanf( inString, "%lf%c", &theNum, &suffix ); /* convert according to [Gg Mm Kk] */ switch ( suffix ) { case 'G': theNum *= kGiga_to_Unit; break; case 'M': theNum *= kMega_to_Unit; break; case 'K': theNum *= kKilo_to_Unit; break; case 'g': theNum *= kgiga_to_Unit; break; case 'm': theNum *= kmega_to_Unit; break; case 'k': theNum *= kkilo_to_Unit; break; default: break; } return (int) theNum; } /* end byte_atof */ /* ------------------------------------------------------------------- * constants for byte_printf * ------------------------------------------------------------------- */ /* used as indices into kConversion[], kLabel_Byte[], and kLabel_bit[] */ enum { kConv_Unit, kConv_Kilo, kConv_Mega, kConv_Giga }; /* factor to multiply the number by */ const double kConversion[] = { 1.0, /* unit */ 1.0 / 1024, /* kilo */ 1.0 / 1024 / 1024, /* mega */ 1.0 / 1024 / 1024 / 1024 /* giga */ }; /* factor to multiply the number by for bits*/ const double kConversionForBits[] = { 1.0, /* unit */ 1.0 / 1000, /* kilo */ 1.0 / 1000 / 1000, /* mega */ 1.0 / 1000 / 1000 / 1000 /* giga */ }; /* labels for Byte formats [KMG] */ const char* kLabel_Byte[] = { "Byte", "KByte", "MByte", "GByte" }; /* labels for bit formats [kmg] */ const char* kLabel_bit[] = { "bit", "Kbit", "Mbit", "Gbit" }; /* ------------------------------------------------------------------- * byte_snprintf * * Given a number in bytes and a format, converts the number and * prints it out with a bits or bytes label. * B, K, M, G, A for Byte, Kbyte, Mbyte, Gbyte, adaptive byte * b, k, m, g, a for bit, Kbit, Mbit, Gbit, adaptive bit * adaptive picks the "best" one based on the number. * outString should be at least 11 chars long * (4 digits + space + 5 chars max + null) * 根据格式及数值输出相应的形如3M的字符串(与上面的相反) * ------------------------------------------------------------------- */ void byte_snprintf( char* outString, int inLen, double inNum, char inFormat ) { int conv; const char* suffix; const char* format; /* convert to bits for [bkmga] */ if ( ! isupper( (int)inFormat ) ) { inNum *= 8; } switch ( toupper(inFormat) ) { case 'B': conv = kConv_Unit; break; case 'K': conv = kConv_Kilo; break; case 'M': conv = kConv_Mega; break; case 'G': conv = kConv_Giga; break; default: case 'A': { double tmpNum = inNum; conv = kConv_Unit; if ( isupper((int)inFormat) ) { while ( tmpNum >= 1024.0 && conv <= kConv_Giga ) { tmpNum /= 1024.0; conv++; } } else { while ( tmpNum >= 1000.0 && conv <= kConv_Giga ) { tmpNum /= 1000.0; conv++; } } break; } } if ( ! isupper ((int)inFormat) ) { inNum *= kConversionForBits[ conv ]; suffix = kLabel_bit[conv]; } else { inNum *= kConversion [conv]; suffix = kLabel_Byte[ conv ]; } /* print such that we always fit in 4 places */ if ( inNum < 9.995 ) { /* 9.995 would be rounded to 10.0 */ format = "%4.2f %s"; /* ##.# */ } else if ( inNum < 99.95 ) { /* 99.995 would be rounded to 100 */ format = "%4.1f %s"; } else { format = "%4.0f %s"; /* #### */ } snprintf( outString, inLen, format, inNum, suffix ); } /* end byte_snprintf */ /* ------------------------------------------------------------------- * redirect * * redirect the stdout into a specified file * return: none * 重定向输出文件名 * ------------------------------------------------------------------- */ void redirect(const char *inOutputFileName) { #ifdef WIN32 FILE *fp; if ( inOutputFileName == NULL ) { fprintf(stderr, "should specify the output file name.\n"); return; } fp = freopen(inOutputFileName, "a+", stdout); if ( fp == NULL ) { fprintf(stderr, "redirect stdout failed!\n"); return; } #endif return; } #ifdef __cplusplus } /* end extern "C" */ #endif