The fputs function writes the string pointed to the output stream. The terminating null character is not written to the file. It takes two argument pointer to string and file pointer.
Syntax of fputs in C
int fputs(const char * restrict s, FILE * restrict stream);
Return value of fputs():
On success, the fputs function returns a non-negative value and if a write error occurs, then returns EOF.
Example code of fputs in C,
#include <stdio.h> int main() { //file pointer FILE *fp = NULL; fp = fopen("aticleworld.txt", "w"); if(fp == NULL) { printf("Error in creating the file\n"); exit(1); } fputs("Hello There, I hope this article will help!",fp); //close the file fclose(fp); printf("File has been created successfully\n"); return 0; }
Output:
You can also see the below Articles,
Difference between puts() and fputs()
There is the following difference between the fputs and puts function.
1. fputs function takes two arguments first is the address of a string, and second is a file pointer. In another hand, puts takes only one argument address of a string.
int puts(const char *s);
int fputs(const char * restrict s, FILE * restrict stream);
2. fputs function can write on any specified file stream while puts only write on stdout (console).
3. Unlike puts(),fputs() does not append a newline when it prints. Let see an example to understand this statement.
#include <stdio.h> int main() { //file pointer FILE *fp = NULL; fp = fopen("aticleworld.txt", "w"); if(fp == NULL) { printf("Error in creating the file\n"); exit(1); } //Print Message on file fputs("I am first Line.",fp); fputs("I am Second Line.",fp); //close the file fclose(fp); //Print Message on console puts("I am first Line."); puts("I am Second Line."); return 0; }
Output:
In the above example, you can see that puts append new line when it prints. So the statements “I am the second line.” is printing at the second line. But besides that fputs does not append a new line. So both statements print on the same line.
Recommended Articles for you:
- How to use fgetc() in C?
- How to use fgets() in C?
- Break Statements in C.
- Continue statement in C.
- File Handling in C, In Just A Few Hours!
- Format specifiers in C.
- A brief description of the pointer in C.
- Dangling, Void, Null and Wild Pointers.
- How to use fread() in C?
- How to use fwrite() in C?
- Function pointer in c, a detailed guide
- How to use the structure of function pointer in c language?
- Function pointer in structure.
- How to use fopen() in C?