温馨提示×

linux fprintf格式化输出技巧有哪些

小樊
84
2024-08-27 00:38:26
栏目: 智能运维

fprintf 是一个用于将格式化的输出写入文件流的 C 语言函数

  1. 输出整数、浮点数和字符串:

    #include<stdio.h>
    
    int main() {
        int a = 42;
        float b = 3.14;
        const char *s = "Hello, World!";
    
        FILE *file = fopen("output.txt", "w");
        if (file == NULL) {
            printf("Error opening file.\n");
            return 1;
        }
    
        fprintf(file, "Integer: %d\n", a);
        fprintf(file, "Float: %.2f\n", b);
        fprintf(file, "String: %s\n", s);
    
        fclose(file);
        return 0;
    }
    
  2. 输出十六进制和八进制数:

    fprintf(file, "Hexadecimal: %x\n", a);
    fprintf(file, "Octal: %o\n", a);
    
  3. 输出指针地址:

    void *ptr = &a;
    fprintf(file, "Pointer address: %p\n", ptr);
    
  4. 输出带有前导零的整数:

    fprintf(file, "With leading zeros: %04d\n", a);
    
  5. 输出带有左对齐或右对齐的文本:

    fprintf(file, "Left-aligned: %-10s\n", s);
    fprintf(file, "Right-aligned: %10s\n", s);
    
  6. 输出科学计数法表示的浮点数:

    fprintf(file, "Scientific notation: %e\n", b);
    
  7. 使用变长参数列表(va_list)实现自定义格式化输出函数:

    #include <stdarg.h>
    
    void custom_fprintf(FILE *file, const char *format, ...) {
        va_list args;
        va_start(args, format);
        vfprintf(file, format, args);
        va_end(args);
    }
    
    int main() {
        // ... (open the file and declare variables)
        custom_fprintf(file, "Integer: %d\n", a);
        custom_fprintf(file, "Float: %.2f\n", b);
        custom_fprintf(file, "String: %s\n", s);
        // ... (close the file)
    }
    

这些技巧可以帮助你更有效地使用 fprintf 函数。请注意,在实际编程中,始终要确保正确处理文件操作(如打开、写入和关闭文件)以及错误检查。

0