fputc() function in C++

In this guide, you will learn what is fputc() function is in C++ programming and how to use it with an example.

1. fputc() Function Overview

The fputc() function, a member of the <cstdio> library in C++, is used to write a character to a given file stream. It advances the position indicator of the stream and writes the character to the position currently pointed by the indicator.

Signature:

int fputc(int char, FILE* stream);

Parameters:

- char: The character to be written. Although this parameter is an int, the function internally converts it to an unsigned char.

- stream: Pointer to the FILE object that identifies the output file stream.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    FILE *fp;

    // Open the file in write mode
    fp = fopen("output.txt", "w");
    if(fp == NULL) {
        std::cerr << "Error opening the file." << std::endl;
        return 1;
    }

    const char* str = "Hello, World!";
    int i = 0;

    while(str[i]) {
        fputc(str[i], fp);
        i++;
    }

    // Close the file
    fclose(fp);

    std::cout << "Text written to output.txt" << std::endl;

    return 0;
}

Output:

Text written to output.txt

3. Explanation

1. A FILE pointer named fp is employed to manage file operations.

2. The "output.txt" file is opened in write mode using the fopen() function.

3. A while loop is used to go through each character of the str string. Each character is written to the file using the fputc() function.

4. After writing all characters to the file, we close it using the fclose() function.

Note: It's crucial to confirm the file's successful opening before attempting to write or conduct other operations. Also, always remember to close the file post-usage to release system resources.


Comments