C programming fgets stdio.h


char *fgets(char * restrict s , int n ,
FILE * restrict stream);

Parameters:
s -The array to which the string is to be stored.

n -This argument signify the number of characters to be read from the ‘stream’.At most ‘n-1’ characters is read from the ‘stream’.

stream -The stream from which the string is to be read.

Return type
char* -Return ‘s’ if successful.If end-of-file is encountered and no characters have been read into the array,the contents of the array remain unchanged and a null pointer is returned.If a read error occurs during the operation,the array contents are indeterminate and a null pointer is returned.

In C programming the <stdio.h> fgets function reads at most one less than the number of characters specified by ‘n’ from the stream pointed to by stream into the array pointed to by ‘s’.A code example is given below.Consider that we have a file name ‘text.txt’ with the string “New string 124345 66 255“.

->C fopen stdio.h

Code example

FILE *fp = fopen(“text.txt” , “r”);
char arr[10] , *ca ;

int c ;

if (fp != NULL)
{
while ( (ca=fgets(arr , 10 , fp )) !=NULL )
{
printf(“%s\n” , arr);
}
}
else
 fprintf(stderr , “File opening failed”);

fclose( fp );

Output,

New strin
g 124345
66 255

If you count the number of characters in ‘arr’ in each output line it turns out to be 9;which is 10-1,except for the last string which of course is due to reaching of EOF.

->C fclose stdio.h





Point to note

In using ‘fgets’ if newline(‘\n’) is encountered while reading characters then only the characters up to that point-the newline character- is stored in the specified array whether the number of characters read has reached ‘n-1’ or not.SImply put if newline is encountered only the characters up to that point is read.A code example is given below.For this example consider a file ‘new.txt’ with the content,
1234565
3949 n
happy new Man

Code example

FILE *fp = fopen(“new.txt” , “r”);

char arr[10] , *ca ;

int c ;

if (fp != NULL)
{
while ( (ca=fgets(arr , 10 , fp )) !=NULL )
{
printf(“%s\n” , arr);
}
}
else
 fprintf(stderr , “File opening failed”);

fclose( fp );

Output,

1234565

3949 n

happy new
Man

If you read the number of characters in each output the number of character is not 9 but lesser except for third output,since newline is encountered in each interval only the characters up to that point is read and stored in ‘arr’ in each ‘fgets’ call.


Related links

->C fgetc stdio.h

->C fprintf stdio.h

->C getchar stdio.h