How To Use The C Library Function Fprintf()

Function Prototype

The fprintf() function has the prototype: int fprintf(FILE *stream, const char *format, ...). It writes formatted output to a file or stream.

Opening a File

Before using fprintf(), open a file using fopen(). For example: FILE *file = fopen("output.txt", "w"); ensures that the file is ready for writing.

Format String

The format argument defines how the data will be printed. Similar to printf(), it uses placeholders like %d, %s, %f for different data types.

Writing to a File

Call fprintf() to write data. Example: fprintf(file, "Hello, %s!\n", name); writes a formatted string to the file, where name is a variable.

Return Value

fprintf() returns the number of characters written or a negative value if an error occurs. Always check the return value to ensure successful writing.

Closing the File

After using fprintf(), close the file with fclose(file); to save changes and free resources. This is crucial for file integrity.