The putchar() function is an important function in C programming which is used to read and print a character. But you cannot use format specifiers with this function. If you want to print only one character then putchar() function can be more efficient compared to printf().
This article is going to explore the putchar() function, its syntax, and its return value with examples.
What is the putchar() Function in C?
The putchar() function in C programming is the output function that is used to write the character(s) in the standard output and displays that character(s) to the console. This function is included by the standard input/output library that is <stdio.h> header file. This function uses a simple syntax in the C language which is given as:
Parameter: This function accepts only one parameter which is the char that is required to write to the output stream.
Return Value: On success, the function returns an unsigned char to the console. Otherwise, it returns EOF (End of a File).
How to Use putchar() Function in C?
Consider the following examples to learn the use of putchar() function in C Programming.
Example 1
Let’s follow up with a simple example of reading one character from a program using the putchar() function and displaying it on the console.
Example 2
Here is another C program that demonstrates the working of the putchar() function by reading characters from a string.
main() {
// Declare a string of characters
char str[50] = "Welcome to the linuxhint.";
for (int i = 0; i <= 25; i++) {
//Use putchar() to print the given string of characters to the console
putchar(str[i]);
}
return 0;
}
Example 3
You can also use the putchar() function to read characters from a file and here is an example of such a case.
int main()
{
FILE* file;
char c;
// Opening file in reading mode
file = fopen("file.txt", "r");
if (NULL == file)
{
printf("file can't be opened \n");
}
// Printing what is written in file, using putchar(), character by character using loop.
do {
c = fgetc(file);
putchar(c);
// Checking if the character is not EOF. If it is EOF stop reading.
} while (c != EOF);
// Closing the file
fclose(file);
return 0;
}
Output
Conclusion
The putchar() function is an important function in C programming used to print a character to the console. While it doesn’t allow special formats, it is more useful than printf() when printing just one character. It is easy to use and use in C programs with its simple syntax and return value. Use examples are provided for reading characters from user input, strings, and data to make it easier for you to understand how to use putchar() in different common situations.