codescracker


c

C fgets()



« Previous Function Next Function »


fgets()

The fgets function reads up to the num-1 characters from stream and stores then in character array pointer to by str. Character are read until either a newline or an EOF is received or until the specified limit is reached. After the characters have been read, a null is stored in the array immediately after the last character read. A newline character will be retained and will be the part of array pointed to by str.

fgets() Syntax

#include<stdio.h>
char *fgets(char *str, int num, FILE *stream);

fgets returns str on success, otherwise a null pointer is returned upon failure.

fgets() Example

Following c program uses fgets() function to display the contents of the text file:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
	clrscr();
	FILE *fp;
	char fname[20], str[128];
	printf("Enter the file name with extension (like demo.txt) : ");
	gets(fname);
	fp=fopen(fname, "r");
	if(fp==NULL)
	{
		printf("Error in opening the file..!!\n");
		printf("Press any key to exit..\n");
		getch();
		exit(1);
	}
	while(!feof(fp))
	{
		if(fgets(str, 126, fp))
		{
			printf("%s",str);
		}
	}
	fclose(fp);
	getch();
}

« Previous Function Next Function »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test