C fputs function

How to write the character array or string data to a File using fputs in C Programming with an example? The C fputs function is 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 the 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 C 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, a file pointer that holds the address and the operation mode

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

Sample text File 1

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

C fputs Example

The C fputs function is 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.

#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 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 the file name because my application and the txt 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 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 the 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

fputs (name, fileAddress);

Next, we close the C programming file pointer.

fclose(fileAddress);

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

C FPUTS function 2