How to use fputs in C

How to use fputs in C

The fputs function writes the string pointed to the output stream. The terminating null character is not written to the file. It takes two argument pointer to string and file pointer.

Syntax of fputs in C

int fputs(const char * restrict s, FILE * restrict stream);

 

Return value of fputs():

On success, the fputs function returns a non-negative value and if a write error occurs, then returns EOF.

Example code of fputs in C,

 

#include <stdio.h>
 
int main()
{
    //file pointer
    FILE *fp = NULL;
    fp = fopen("aticleworld.txt", "w");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }
 
    fputs("Hello There, I hope this article will help!",fp);
    //close the file
    fclose(fp);
 
    printf("File has been created successfully\n");
 
    return 0;
}

Output:

fputs in c

 

You can also see the below Articles,

Difference between puts() and fputs()

There is the following difference between the fputs and puts function.

1. fputs function takes two arguments first is the address of a string, and second is a file pointer. In another hand, puts takes only one argument address of a string.

int puts(const char *s);
int fputs(const char * restrict s, FILE * restrict stream);

2. fputs function can write on any specified file stream while puts only write on stdout (console).

3. Unlike puts(),fputs() does not append a newline when it prints.  Let see an example to understand this statement.

#include <stdio.h>

int main()
{
    //file pointer
    FILE *fp = NULL;
    fp = fopen("aticleworld.txt", "w");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }
    //Print Message on file
    fputs("I am first Line.",fp);
    fputs("I am Second Line.",fp);
    //close the file
    fclose(fp);

    //Print Message on console
    puts("I am first Line.");
    puts("I am Second Line.");


    return 0;
}

Output:

Difference between fputs and puts

In the above example, you can see that puts append new line when it prints. So the statements “I am the second line.” is printing at the second line. But besides that fputs does not append a new line. So both statements print on the same line.

Recommended Articles for you:



Leave a Reply

Your email address will not be published. Required fields are marked *