简体   繁体   English

C 中的 Fprintf 实现

[英]Fprintf implementation in C

Hi I want to write base implementation of fprintf function in C.嗨,我想在 C 中编写fprintf function 的基本实现。 I have problem with the void cast.我对 void 演员有疑问。 It says that it is incompatible type for argument 2 of write .它说它是write的参数 2 的不兼容类型。 I tried several ways to do it but nothing changes.我尝试了几种方法来做到这一点,但没有任何改变。 Thats the function:那就是 function:

void myfprintf(int fd, char *format, void *value) {
    if(strcmp(format,"%d")){
        write(fd,(*(int*)value),sizeof(int));
    }
    if(strcmp(format,"%f")){
        write(fd,(*(float*)value),sizeof(float));
    }
    if(strcmp(format,"%lf")){
        write(fd,(*(double*)value),sizeof(double));
    }
}

For start I want to print int double and float types.首先,我想打印 int double 和 float 类型。

To implement an fprintf-like function you should declare your function with ellipsis,要实现类似 fprintf 的 function,您应该使用省略号声明 function,

int myprintf(int fd, char *format, ...);

then use the so called 'var_args' (variable arguments) tools to access argument.然后使用所谓的“var_args”(变量参数)工具来访问参数。 See the manual pages on va_start(), va_arg(), va_end().请参阅 va_start()、va_arg()、va_end() 的手册页。 These tools are macros that properly walk the values and pointers on your stack.这些工具是正确遍历堆栈上的值和指针的宏。 The stack arrangement is machine-architecture and implementation dependent, and those dependencies are hidden in the var args macro implementation.堆栈排列是机器架构和实现相关的,这些依赖关系隐藏在 var args 宏实现中。

You'll find examples here: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/ldbl-opt/nldbl-compat.c;h=2b1261acc7505d9a6ac3f25b76bafb9118854ef8;hb=HEAD You'll find examples here: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/ldbl-opt/nldbl-compat.c;h=2b1261acc7505d9a6ac3f25b76bafb9118854ef8;hb=头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM