C Language



Admission Enquiry Form

  

Write a String(fputs() function) in C File Handling




Write a String into a File in C File Handling

We can also write a string into the file in C file handling by using fprintf() or by using fputs().

1. Example to write a string using fprintf() into a file:

#include<stdio.h>
void main()
{
FILE *fptr;
fptr=fopen("compuhelp.txt","w");

if(fptr==NULL)
{
printf("\n File could not be opened ");
}
else
{
fprintf(fptr,"I am using C to create files.");
}
printf("\n data saved into the file");
fclose(fptr);
}


Output:

data saved into the file

Now, when we compile and run the above program, this will create a file compuhelp.txt with the following content:





2. Example to write a String using fputs() into a file:

#include<stdio.h>
void main()
{
FILE *fptr;
fptr=fopen("compuhelp.txt","w+");

if(fptr==NULL)
{
printf("\n File could not be opened ");
}
else
{
fputs("This is c file handling.", fptr);
fputs("Here is the use of fputs().", fptr);
}
printf("\n string saved into the file using fputs()");
fclose(fptr);
}


string saved into the file using fputs()


Now, when we compile and run the above program, this will create a file compuhelp.txt with the following content: