C putc() Function Tutorial

In this section, we will learn what the putc() function is and how it works in C.

C putc() Function

The `putc()` function is used to send a character to a file.

This function only takes one character at a time and sends it to the target file. But if we want to send a character-string to a file in one call, we can use a function like `fputs()`.

The prototype of the function exists in the `stdio.h` header file and so we need to include the header file in order to work with the function.

C putc() Function Syntax:

Here’s the prototype of the `getc` function:

int putc(int char, FILE *stream)

C putc() Function Parameters

The first argument of the function is the character that we want to send to the target file.

The second argument is the address of a pointer to the FILE-structure of the target file.

Note: we get this pointer from the call to the `fopen` function.

C putc() Function Return Value

The function returns either the character set as its first argument on a successful operation or EOF if an error occurred.

Example: using putc() function in C

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main() {

    //Call the the fopen function in order to open the file in write mode.
    FILE *file = fopen("G:/fileOne.txt","w");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        exit(EXIT_FAILURE);
    }

    char *string = "Hello,\nMy name is John Doe!\n";
    for (int i = 0 ; i<strlen(string);i++){
        fputc(*(string+i), file);
    }

    fclose(file);


    printf("Done\n");
    return 0;
}

Output:

Done

Note: in order to write content to a file, the file should be opened in one of the modes that allows for writing content. (“w”, “w+”, “a”, “a+” etc.)

In this example, we wrote the content of the `string` into the file named `fileOne.txt`. As a result, if we open the file after the execution of the program, the content of the `string` variable will be there.

Note: The file is opened in `w` mode, which means the content of the file (if any) will be truncated to zero length or the file will be created if it doesn’t exist.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies