putc() function in C language with Example

Here, we are going to learn about the putc() function of library function stdio.h in C language with its syntax, example.
Submitted by Souvik Saha, on February 22, 2019

putc() function in C

The putc() function is defined in the <stdio.h> header file.

Prototype:

    int putc(const char ch, FILE *filename);

Parameters: const char ch, FILE *filename

Return type: int

Use of function:

In the file handling, through the putc() function, we write the character from the stdin to the input file stream and increments the file position pointer. The prototype of the function putc() is int putc(const char* string, FILE *filename);

It returns an integer value which is conversion of an unsigned char. It also returns EOF, if an error occurs. Whenever there is a binary file check for error with the function ferror()

putc() example in C

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Initialize the file pointer
    FILE* f;
    char ch;

    //Create the file for write operation
    f = fopen("includehelp.txt", "w");

    printf("Enter five character\n");
    for (int i = 0; i < 5; i++) {
        //take the characters from the users
        scanf("%c", &ch);
        //write back to the file
        putc(ch, f);
        //clear the stdin stream buffer
        fflush(stdin);
    }

    //close the file after write operation is over
    fclose(f);

    //open a file
    f = fopen("includehelp.txt", "r");
    printf("Write operation is over and file is reday for read operation\n");
    printf("\n...............print the characters..............\n\n");
    while (!feof(f)) {
        //takes the characters in the character array
        ch = getc(f);
        //and print the characters
        printf("%c\n", ch);
    }

    fclose(f);

    return 0;
}

Output

putc() example in C language

C stdio.h Library Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.