In C Language, "fputc()" is a function used to write a single character to a file.
It's part of the standard input/output library defined in the "stdio.h" header file.
"fputc" function is more efficient than functions like "fprintf()" when writing single characters.
"fputc()" is easy to use for writing individual characters to a file and automatically handles buffering for better performance.
"fputc()" is similar to "putc()" and "putchar()", but it allows us to specify the file stream to which the character should be written.
File Output: It enables us to write individual characters to files, allowing us to write character-by-character.
Error Handling: The return value of `fputc()` can be used to check for errors during the write operation in file.
#include <stdio.h> int fputc(int character, FILE *stream);
"character": This is an integer value representing the character to be written to the file. It's implicitly converted to an unsigned char before being written.
"stream": This is a pointer to the file stream where you want to write the character. It should be obtained by opening a file using "fopen()" or be one of the standard streams like "stdout", "stderr", etc.
#include <stdio.h> int main() { FILE *file_ptr; char filename[] = "example.txt"; char ch = 'A'; // Open a file for writing file_ptr = fopen(filename, "w"); if (file_ptr == NULL) { printf("Error opening the file.\n"); return 1; // Return error status } // Write a character to the file if (fputc(ch, file_ptr) == EOF) { printf("Error writing to the file.\n"); fclose(file_ptr); return 1; // Return error status } // Close the file stream fclose(file_ptr); printf("Character written to the file successfully.\n"); return 0; // Return success status }
We open a file named "example.txt" for writing using "fopen()".
We use "fputc()" to write the character 'Z' to the file.
The return value of "fputc()" is checked for EOF (end-of-file), which indicates an error occurred during writing.
Finally, we close the file stream using "fclose()".
After running this program, the "example.txt" file will be created (or overwritten if it already exists) with the character 'Z' written to it.
Always remember to close files after we finish using them to release resources properly.