Latest web development tutorials

C library functions - fgets ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionschar * fgets (char * str, int n, FILE * stream) reads a line from the specified flow stream, and stores it in strpoints to the string. When reading(n-1) character, or read when line breaks, or end of file, it will stop, as the case may be.

statement

Here is () statement fgets function.

char *fgets(char *str, int n, FILE *stream)

parameter

  • str - This is a pointer to a character array, the array stores the string to be read.
  • n - This is the maximum number of characters to read (including the final null character).Use the array length is usually passed to the str.
  • stream - This is a pointer to FILE pointer to an object, the object identifier FILE read from a character stream.

return value

If successful, the function returns the same str parameter. If you reach the end of the file or not to read any characters, str contents remain unchanged, and returns a null pointer.

If an error occurs, it returns a null pointer.

Examples

The following example demonstrates the fgets () function is used.

#include <stdio.h>

int main()
{
   FILE *fp;
   char str[60];

   /* 打开用于读取的文件 */
   fp = fopen("file.txt" , "r");
   if(fp == NULL) {
      perror("打开文件时发生错误");
      return(-1);
   }
   if( fgets (str, 60, fp)!=NULL ) {
      /* 向标准输出 stdout 写入内容 */
      puts(str);
   }
   fclose(fp);
   
   return(0);
}

Suppose we have a text filefile.txt, it reads as follows.As an example of the file, enter:

We are in 2014

Let's compile and run the above program, which will result in the following:

We are in 2014

C standard library - <stdio.h> C standard library - <stdio.h>