fputs() Function

The fputs() function in C writes a string to a specified stream. It begins copying the content from the provided memory address until it reaches the terminating null character, which is not written to the stream. Unlike puts(), it allows the programmer to choose the destination stream and does not append a newline automatically.


Syntax of fputs()

</>
Copy
int fputs(const char *str, FILE *stream);

Parameters

ParameterDescription
strA C string containing the content to be written to the stream.
streamA pointer to a FILE object that identifies the output stream.

It is worth mentioning that fputs() writes the string exactly as provided, stopping at the null terminator and not adding any extra characters like a newline. This makes it ideal for precise control over the output format.

Return Value

On success, fputs() returns a non-negative value. On error, it returns EOF and sets the error indicator for the stream.


Examples for fputs()

Example 1: Writing a String to Standard Output

This example demonstrates the basic use of fputs() to write a string to the standard output stream.

Program

</>
Copy
#include <stdio.h>

int main() {
    const char *message = "Hello, World!";
    
    // Write the string to the standard output stream
    fputs(message, stdout);
    
    return 0;
}

Explanation:

  1. A constant string "Hello, World!" is defined.
  2. fputs() is used to write the string to stdout.
  3. No newline character is appended, so the output appears exactly as the string.

Program Output:

Hello, World!

Example 2: Writing a String to a File

This example illustrates how to use fputs() to write a string to a file.

Program

</>
Copy
#include <stdio.h>

int main() {
    const char *text = "This is a sample text.";
    FILE *file = fopen("output.txt", "w");
    
    if (file != NULL) {
        // Write the text to the file
        fputs(text, file);
        fclose(file);
    } else {
        perror("Error opening file");
    }
    
    return 0;
}

Explanation:

  1. A constant string "This is a sample text." is defined.
  2. The file output.txt is opened for writing.
  3. If the file opens successfully, fputs() writes the string to the file, and the file is closed.
  4. If the file fails to open, an error message is displayed using perror().

Program Output:

This is a sample text.

Example 3: Writing a String without an Automatic Newline

This example shows that fputs() writes the string exactly as provided, without appending a newline at the end.

Program

</>
Copy
#include <stdio.h>

int main() {
    const char *line = "Line without newline";
    
    // Write the string to stdout without appending a newline
    fputs(line, stdout);
    
    return 0;
}

Explanation:

  1. A constant string "Line without newline" is defined.
  2. fputs() writes the string to stdout without adding a newline character.
  3. The output remains exactly as the string provided.

Program Output:

Line without newline