What is fputs() in C?

fputs() is a standard C library function that is used to write a string of characters to a file at the location indicated by the file pointer. Below is the declaration of the fputs() function:

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

The fputs() function returns 0 if the string is written to the file successfully. EOFEnd-of-File is returned if there is an error when writing to the file.

Parameters of the fputs() function

  • str: String of characters to be written
  • stream: Pointer to the file where the character is to be written

Code

Consider the code snippet below, which uses fputs() to write a string to a file:

#include <stdio.h>
int main() {
FILE * fPointer;
const char * str = "fputs() example code";
fPointer = fopen ("fputsExample.txt", "w");//opening file
fputs(str, fPointer);//writing str to the file
fclose(fPointer);
return 0;
}

Explanation

The fopen() function is used in line 5 to open the file for writing. The fputs() function is used in line 10 to write the string str that is created in line 6 to the file location indicated by fPointer. After writing str to the file successfully, fputs() increments the fPointer by one location so that when the next write operation is applied to the file, the writing begins after the last character of str written by fputs().

The contents of fputsExample.txt after executing the above code will be as follows:

# fputsExample.txt
fputs() example code

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved