The syntax of the fgets()
function is:
Syntax: char *fgets(char *str, int n, FILE *fp);
The function reads a string from the file pointed to by fp
into the memory pointed to by str
. The function reads characters from the file until either a newline ('\n'
) is read or n-1
characters is read or an end of file is encountered, whichever occurs first. After reading the string it appends the null character ('\0'
) to terminate the string. On success, it returns a pointer to str
. On error or end of the file it returns NULL
.
The following program demonstrates how to use fgets()
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include<stdio.h> #include<stdlib.h> int main() { char str[50]; FILE *fp; fp = fopen("myfile2.txt", "r"); if(fp == NULL) { printf("Error opening file\n"); exit(1); |