fputs() function in C++

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

1. fputs() Function Overview

The fputs() function is used to write a string to the specified stream. It writes characters from the string to the stream until the end-of-string null character ('\0') is encountered. The null character is not written to the stream. The function returns EOF if an error occurs, otherwise, it returns a non-negative value.

Signature:

int fputs(const char* str, FILE* stream);

Parameters:

- str: A pointer to the string that needs to be written.

- stream: Pointer to a FILE object that specifies an output stream.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    FILE* fp;
    const char* text = "Hello, fputs()!\n";

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

    // Using fputs to write to the file
    if (fputs(text, fp) == EOF) {
        std::cerr << "Error writing to file.";
        fclose(fp);
        return 1;
    }

    std::cout << "String written to file successfully.";

    // Close the file
    fclose(fp);

    return 0;
}

Output:

String written to file successfully.

3. Explanation

1. We begin by declaring a FILE pointer fp and a constant character pointer text containing a sample message.

2. We then open a file named "sample.txt" in write mode.

3. If the file opens successfully, we use fputs() to write the content of the text to the file.

4. If writing was successful, a success message is printed to the standard output.

5. After writing to the file, we close it using fclose().


Comments