C fputs function

How to write the character array or string data to a File using fputs in C Programming with example?. The C fputs function used to write an array of characters to the specified stream. Use the fputc function to write character by character.

The syntax behind the fputs in C Programming language is as shown below.

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

or we can simply write it as:

int fputs(string, <File Pointer>)

From the above fputs function code snippet,

  • char: Please specify the array of characters you want to write to the file
  • stream: Please specify the pointer to a FILE object. Or say, file pointer that holds the file address and the operation mode

We are going to use the following specified file to demonstrate this C fputs function.

C fputs 1

From the above screenshot, you can observe that the sample.txt file is in our Documents folder and it is empty.

Example for C fputs

The C fputs function used to write the array of characters to the user-specified file. This C program will help you to understand the same.

TIP: You have to include the #include<stdio.h> header before using this fputs function.

// C fputs function example
#include <stdio.h> 

int main()
{
   FILE *fileAddress;
   fileAddress = fopen("sample.txt", "w");
   char name[50];
	
   if (fileAddress != NULL) {
	printf("\n please neter the String that you want to write to the File :\n");
	gets(name);

	// Let us use our fputs
	fputs (name, fileAddress);
	printf("\n We have written the Name successfully");
	fclose(fileAddress);		
   }
   else {
     	printf("\n Unable to Create or Open the Sample.txt File");
   }
   return 0;
}
C FPUTS function 1

Within this C fputs function example, First, we created the File pointer and then assigned the file in write mode. Please refer to fputc function article.

TIP: In this C program, we haven’t mentioned the full path of file name because my application and the text file reside in the same location. If your scenario is different, please provide the full path.

FILE *fileAddress;
fileAddress = fopen("sample.txt", "w");

The following If Statement checks whether we successfully opened the sample.txt file or not.

if (fileAddress != NULL) {

The following statement asks the user to enter the string that he wants to write to the sample.txt, and we are reading the user input using Gets function

printf("\n please neter the String that you want to write to the File :\n");
gets(name);

Next, we used the C fputs function to write the user-specified string to the sample.txt file

fputs (name, fileAddress);

Next, we are closing the C programming file pointer.

fclose(fileAddress);

Let us open the File to see whether we successfully returned the characters or not

C FPUTS function 2