C++ Standard Library C++ STL Library

C++ <cstdio> - fputs() Function



The C++ <cstdio> fputs() function writes every character of the null-terminated string pointed to by str to the output stream stream, until it reaches the terminating null character ('\0'). The terminating null-character is not copied to the stream.

Calling this function is same as calling fputc() function repeatedly. puts() and fputs() are equivalent functions except puts() uses stdout as destination and appends a newline character at the end automatically.

Syntax

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

Parameters

str Specify a null-terminated character string to be written.
stream Specify a pointer to a FILE object that specifies an output stream.

Return Value

On success, returns a non-negative value. On failure, returns EOF and sets the error indicator ferror().

Example:

In the example below, the file test.txt is opened in write mode.The program creates an empty file for output operations if the file does not exist. If the file already exists, its contents are discarded and the file is treated as a new empty file. Finally it writes C string in the file before closing it.

#include <cstdio>
 
int main (){
  //open the file in write mode
  FILE *pFile = fopen("test.txt", "w");
  
  //writes str in the file
  char str[50] = "Hello World!";
  fputs(str, pFile);
  
  //close the file
  fclose(pFile);
  
  //open the file in read mode to read
  //the content of the file
  pFile = fopen("test.txt", "r");
  int c = fgetc(pFile);
  while (c != EOF) {
    putchar(c);
    c = fgetc(pFile);
  }

  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

Hello World!

❮ C++ <cstdio> Library