A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_fputs.htm below:

C Standard Library fputs Function

C Library - fputs() function

The C library int fputs(const char *str, FILE *stream) function writes a string to the specified stream up to but not including the null character.It is commonly used for writing text to files.

Syntax

Following is the C library syntax of the fputs() function −

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

This function accept two parameters −

Return value

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

Example 1: Writing a String to a File

This example writes a simple string to a text file.

Below is the illustration of C library fputs() function.

#include <stdio.h>

int main() {
    FILE *file = fopen("example1.txt", "w");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }
    
    if (fputs("Hello, World!\n", file) == EOF) {
        perror("Failed to write to file");
        fclose(file);
        return 1;
    }
    
    fclose(file);
    return 0;
}
Output

The above code opens a file named example1.txt for writing, writes "Hello, World!" to it, and then closes the file. −

Hello, World!
Example 2: Writing Multiple Lines to a File

This example writes multiple lines to a file using fputs in a loop.

#include <stdio.h>

int main() {
    FILE *file = fopen("example3.txt", "w");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }
    
    const char *lines[] = {
        "First line\n",
        "Second line\n",
        "Third line\n"
    };
    
    for (int i = 0; i < 3; ++i) {
        if (fputs(lines[i], file) == EOF) {
            perror("Failed to write to file");
            fclose(file);
            return 1;
        }
    }
    
    fclose(file);
    return 0;
}
Output

After execution of above code,it writes three different lines to example3.txt by iterating through an array of strings and using fputs in each iteration.

First line
Second line
Third line

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4