printf原理及实现
Posted 5念since
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了printf原理及实现相关的知识,希望对你有一定的参考价值。
内核中的printk
kernel\\printk\\printk.c
asmlinkage __visible int printk(const char *fmt, ...)
va_list args;
int r;
va_start(args, fmt);
r = vprintk_func(fmt, args);
va_end(args);
return r;
EXPORT_SYMBOL(printk);
include\\acpi\\platform\\acgcc.h
typedef __builtin_va_list va_list;
#define va_start(v, l) __builtin_va_start(v, l)
#define va_end(v) __builtin_va_end(v)
…再往下还得再分析
printf实现
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
int my_printf(const char* string,...);
int main()
int i = 10000;
my_printf("hello world!\\n");
my_printf("int i = %d, j = %d", i, 10);
my_printf("char i = %c", 50);
system("pause") ;
return 0;
int my_printf(const char* string,...)
char buffer[BUFSIZ] = 0;//Be tolerant with my_printf, never try to jump ovet the band of the buffer -- buffer overflow
int temp = 0;
va_list arg;
char* p_string = NULL;
char* p_buffer = buffer;
char* p_temp = NULL;
int counter = 0;
int number = 0;
int foo = 0;
va_start(arg,string);
for(counter = 0,p_string = string;*(p_string) != '\\0';)
switch(*p_string)
case '%':
p_string++;
switch(*p_string)
case 'd':
temp = va_arg(arg,int);
foo = temp;
while(foo)
number++;
counter++;
foo /= 10;
foo = temp;
temp = number;
while(number)
*(p_buffer+number-1) = (foo%10) + '0';
foo /= 10;
number--;
p_buffer += temp;
break;
case 'c':
temp = va_arg(arg,int);
*(p_buffer++) = temp;
break;
case 's':
p_temp = va_arg(arg,char*);
while(p_temp != NULL)
*(p_buffer++) = *(p_temp++);
counter++;
break;
default:
break;
p_string++;
break;
default:
*(p_buffer++) = *(p_string++);
counter++;
va_end(arg);
p_buffer = NULL;
puts(buffer);
return counter;
以上是关于printf原理及实现的主要内容,如果未能解决你的问题,请参考以下文章