putc() Function
The putc()
function in C writes a character to the specified stream and advances the stream’s internal position indicator. It is used for outputting characters to files or other output streams and may be implemented as a macro in some libraries, which can affect how the stream expression is evaluated.
Syntax of putc()
int putc(int character, FILE *stream);
Parameters
Parameter | Description |
---|---|
character | The integer promotion of the character to be written. It is internally converted to an unsigned char. |
stream | A pointer to a FILE object that identifies the output stream. |
The putc()
function writes the specified character at the position indicated by the stream’s internal pointer and then advances the pointer by one. Note that because some libraries may implement putc()
as a macro, the expression passed for the stream should be free of side effects.
Return Value
On success, putc()
returns the character written. If an error occurs during writing, it returns EOF
and sets the error indicator for the stream.
Examples for putc()
Example 1: Writing a Single Character to a File
This example demonstrates how to use putc()
to write a single character to a file.
Program
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// Write the character 'A' to the file
putc('A', fp);
fclose(fp);
return 0;
}
Explanation:
- A file named “output.txt” is opened in write mode.
- The
putc()
function writes the character'A'
to the file. - The file is closed after writing.
Program Output:
A
Example 2: Writing Multiple Characters to Standard Output
This example uses putc()
to write a sequence of characters to the standard output (stdout).
Program
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int i = 0;
// Write each character to stdout using putc()
while (str[i] != '\0') {
putc(str[i], stdout);
i++;
}
return 0;
}
Explanation:
- A string
"Hello, World!"
is defined. - A while loop iterates through each character of the string.
- Each character is written to the standard output using
putc()
.
Program Output:
Hello, World!
Example 3: Error Handling with putc()
This example demonstrates basic error handling when using putc()
to write to a file.
Program
#include <stdio.h>
int main() {
FILE *fp = fopen("readonly.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// Attempt to write to a file opened in read mode
if (putc('X', fp) == EOF) {
perror("Error writing character");
}
fclose(fp);
return 0;
}
Explanation:
- The program attempts to open a file “readonly.txt” in read mode.
- If the file cannot be opened, an error message is displayed and the program exits.
- An attempt is made to write the character
'X'
to the file usingputc()
. - Since the file is opened in read mode, the write operation fails,
putc()
returnsEOF
, and an error message is printed.
Program Output:
Error writing character: [Error message from perror]