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()
int fputs(const char *str, FILE *stream);
Parameters
Parameter | Description |
---|---|
str | A C string containing the content to be written to the stream. |
stream | A 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
#include <stdio.h>
int main() {
const char *message = "Hello, World!";
// Write the string to the standard output stream
fputs(message, stdout);
return 0;
}
Explanation:
- A constant string
"Hello, World!"
is defined. fputs()
is used to write the string tostdout
.- 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
#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:
- A constant string
"This is a sample text."
is defined. - The file
output.txt
is opened for writing. - If the file opens successfully,
fputs()
writes the string to the file, and the file is closed. - 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
#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:
- A constant string
"Line without newline"
is defined. fputs()
writes the string tostdout
without adding a newline character.- The output remains exactly as the string provided.
Program Output:
Line without newline