fgets() and fputs() in C

Previous
Next

fgets():

  • It is used to read specified number of characters(String) at a time.
  • Prototype is :
    • char*   fgets(char* str, int size, FILE* stream);
  • It reads “size” bytes from specified “stream” and stores into “str”.
  • On Success, it returns the pointer to string that has read.
  • On failure, it returns NULL pointer.

Note: It reads only size-1 characters into String every time. Last character of every string is null(\0) by default.

#include<stdio.h>
int main()
{
	FILE* p;
	char str[10];
	p = fopen("code.c", "r");
	if(p==NULL){
		printf("No such file to open \n");
	}
	else
	{
		fgets(str, 10, p);
		printf("The string is : %s \n", str);	
		fclose(p);
	}
	return 0;
}

Reading the complete file using fgets():

#include<stdio.h>
int main()
{
	FILE* p;
	char str[10];
	p = fopen("code.c", "r");
	if(p==NULL){
		printf("No such file to open \n");
	}
	else
	{
		while(fgets(str, 10, p))
		{
			printf("%s \t", str);
		}	
		fclose(p);
	}
	return 0;
}

fputs():

  • A pre-defined function is used to write a string on to the file.
  • Prototype is:

void  fputs(char* str , FILE* stream);

#include<stdio.h>
int main()
{
	FILE *src, *dest;
	char str[10];
	src = fopen("code.c", "r");
	if(src==NULL){
		printf("No such file to open \n");
	}
	else
	{
		dest = fopen("data.txt", "w");
		while(fgets(str, 10, src))
		{
			fputs(str, dest);
		}
		printf("Contents copied...\n");	
		fclose(src);
		fclose(dest);
	}
	return 0;
}
Previous
Next

Add Comment

Courses Enquiry Form