dprintf is a function in the C programming language used to write formatted output to a file stream. It's similar to the printf function, but instead of printing to the standard output stream (stdout), it allows you to specify a file stream where the output will be directed.

The syntax of dprintf is as follows:

int dprintf(int fd, const char *format, ...);
  • fd: The file descriptor of the file stream where the output will be written.
  • format: A string specifying the format of the output. It can contain format specifiers replaced by the values of subsequent arguments.
  • ...: Additional arguments containing the values to be inserted into the format string.

The return value of dprintf is the number of characters written to the file stream, or -1 if an error occurred.

Here's an example of using dprintf:

#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    int value = 10;
    double pi = 3.14159;

    int result = dprintf(fileno(file), "Value: %d, Pi: %.2f\n", value, pi);
    if (result < 0) {
        printf("Error writing to file.\n");
        return 1;
    }

    fclose(file);

    return 0;
}

In this example, dprintf writes formatted output to a file named 'output.txt'. The format string 'Value: %d, Pi: %.2f\n' includes format specifiers for an integer (%d) and a floating-point number with two decimal places (%.2f). The values of the variables 'value' and 'pi' are inserted into the format string. The resulting output is 'Value: 10, Pi: 3.14\n'. The 'fileno' function obtains the file descriptor from the FILE pointer.

Note that dprintf is a POSIX-specific function and might not be available on all systems.


原文地址: https://www.cveoy.top/t/topic/pSFU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录