- #include <stdarg.h>
- #include <string.h>
- unsigned int write_Int(char* buffer,int value)
- {
- unsigned char stack[10];
- unsigned char length=0;
- char *_temp;
- if(value<0){
- *(buffer++)='-';
- value*=-1;
- }
- do
- {
- stack[length]='0'+(value%10);
- value/=10;
- length++;
- }while(value);
- _temp=length;
- while(length)
- {
- *buffer=stack[length-1];
- length--;
- buffer++;
- }
- return buffer-_temp;
- }
- int sprintf(char* buffer,const char* format,...)
- {
- va_list arg_ptr;
- unsigned int buffer_length=strlen(buffer);
- unsigned int format_length=strlen(format);
- unsigned int index=0;
- int temp;
- char ctemp;
- char* stemp;
- va_start(arg_ptr,format);
- for(index=0;index<format_length;++index)
- {
- if(format[index]!='%')
- (*buffer++)=format[index];
- else
- {
- switch(format[index+1])
- {
- case 'd':
- temp=va_arg(arg_ptr,int);
- buffer=buffer+write_Int(buffer,temp);
- break;
- case 's':
- stemp=(char*)va_arg(arg_ptr,char*);
- strcpy(buffer,stemp);
- buffer+=strlen(stemp);
- break;
- case 'c':
- ctemp=va_arg(arg_ptr,int);
- *(buffer++)=ctemp;
- break;
- }
- index++;
- }
- }
- *buffer=0;
- va_end(arg_ptr);
- return --index;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0312201411166.html
来源: http://www.codesnippet.cn/detail/0312201411166.html