File Operation-Writing


 Writing to the File

 In C programming there are three functions used to write data into a file. If we want to write something into the file then we can use one of the function from the following functions:- fprintf(), fputs() and fputc() functions.

 All the above functions are used to write the contents to a file.Let us discuss each of them one by one :-

1. fprintf() Function

The fprintf() function is used to write data to a file. It writes a set of character into a file.We can write other types of values like int, float etc. into a file by using this method.

Syntax 

int fprintf(FILE *fp, char string[])

The fprintf() function accepts two arguments or parameters. The first one is file pointer which in indicating to the file and the second one is sequence of characters or you can say that array of character means a string.

Program Example 

#include<stdio.h>

int main()
{
        FILE *fp;

        if(fp=fopen("hello.txt", "w"))

        {
            if(fprintf(fp,"c programming")>=0)

            {
                printf("write operation successful by using the fprintf function");
            }
        
        }

        fclose(fp);

        return 0;
}


2. fputs() Function

The fputs() function is used to write a single line of characters into a file. It is used to write a line (Character line) to the file.

Syntax

int fputs(char String[], FILE *fp);

It  takes 2 arguments. The first argument is a string which is to be written  into the file and the second argument is the pointer of the file means a file pointer in which the string is to be written. It returns 1 if the write operation was successful, otherwise, it returns 0.

Program Example

#include<stdio.h>

int main
{
    FILE *fp;

    if(fp=fopen("hello.txt","w"))
    {
        if(fputs("C Programming", fp)>=0)
        {
            printf("String written to the file successful");
        }
    }

    fclose(fp);
    return 0;
}


3. fputc() Function

The fputc() function is used to write a single character to the file. 

Syntax

int fputc(char Character, FILE *fp);

It also takes 2 arguments. The first argument is a Character which is to be written in the file and the second argument is the pointer of the file means a file pointer in which the string is to be written. It returns 1 if the write operation was successful, otherwise, it returns 0.

Program Example

#include<stdio.h>

int main
{
    FILE *fp;

    if(fp=fopen("hello.txt","w"))
    {
        fputc('C'fp)>=0)
    }

    fclose(fp);
    return 0;
}

Output

C will be written to the file.



        


No comments:

Post a Comment