c fputs & fgets

c fputs() & fgets()

fputs() in c

Declaration: int fputs(const char *str, FILE *fptr);
This function fputs(const char *str, FILE *fptr) writes the null terminated string pointer to by str (constant char) to a file associated with file pointer.fptr so the null character that marks the end of string is not written to a file. on the success it returns EOF on error or a non negative value.

/* program to understand the use of fputs() */
#include<stdio.h>
#include<stdlib.h>
int
main()
{
FILE *fptr;
char ch[40];
if ((fptr=fopen("myfile","w"))==NULL)
{
printf("Can't open file Error" );
exit (1);
}
printf("Enter the string \n" );
printf("to stop enter ctrl+d \n" );
while (gets(ch)!=NULL)
{
fputs(ch,fptr);
fclose(fptr);
}
return 0;
}

fgets()

Declaration: char *fgets(char *ch ,int n, FILE *fptr);
This function *fgets(char *ch ,int n, FILE *fptr) is use to read characters from a file and these all characters are stored in the string pointer to ch. It reads n-1 characters from the file and where n is the second argument in the *fgets(char *ch ,int n, FILE *fptr) and the third argument fptr is a file pointer. which is associated with a file. and This function returns the string pointed to by ch on success, and return NULL on error or on end of file

/* program to understand the use of fgets() */
#include<stdio.h>
#include<conio.h>
int
main()
{
char ch[50];
FILE *fptr;
if((fptr=fopen("myfile","r"))==NULL)
{
printf("Error can't open file");
exit(1);
}
while(fgets(ch,50,fptr)!=NULL)
{
puts(ch);
}
fclose(fptr);
return 0;
}