C programming stdio.h function - int fprintf(FILE *stream, const char *format, ...)

https://‮igi.www‬ftidea.com

The fprintf() function in the stdio.h library of C programming language is used to write a formatted string to a specified file stream. The function has the same syntax as printf(), but it writes the formatted output to the specified file stream rather than to standard output.

The function has the following prototype:

int fprintf(FILE *stream, const char *format, ...);

The fprintf() function writes the formatted output to the file stream specified by the stream argument. The formatted string is constructed from the format string and the arguments that follow it, which are specified using the variable argument list syntax of C. The return value of the function is the number of characters written to the file stream, or a negative value if an error occurred.

The format string is a character string that contains conversion specifications, which start with the % character and specify how to format the output. The conversion specifications are replaced by the corresponding argument values, which are passed in the variable argument list.

For example, the following code writes a formatted string to a file named output.txt:

#include <stdio.h>

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

    int x = 42;
    double y = 3.14159;
    char s[] = "hello, world!";

    fprintf(f, "x = %d, y = %f, s = %s\n", x, y, s);

    fclose(f);
    return 0;
}

This code opens the file output.txt for writing, and writes a formatted string to the file using fprintf(). The formatted string includes the values of the variables x, y, and s, which are inserted into the string using the conversion specifications %d, %f, and %s, respectively. The resulting string is written to the file using fprintf(), and the file is closed with fclose().