fgets() C Library Function Usage Examples To Read File

RSS
FACEBOOK
FACEBOOK
PINTEREST
PINTEREST
LINKEDIN
INSTAGRAM

Standard C library provides the fgets() function to read a line from a specified stream where stream can be a file. fgets() function also used to read the specified number or size of the characters from the given string. In this tutorial, we will learn the usage of fgets()  function with its parameters with different examples.

Syntax

The syntax of the fgets()  function is very easy. there are only 3 parameters where we will get a char array as a return value.

Here is the parameters meaning and usage information.

  • char *str is a string value where copied or got string will be stored.
  • int n is the size or count of the read characters.
  • FILE *stream is the stream we want to read which is generally a file.

Return Value

If the function execution is completed successfully there is a return value which is a char. If the end of stream or file is reached and no characters have been read the contents of str remain unchanged and a null pointer is returned.

Read From File Whole Line

Now its time for example. We will create a sample code which will read file file.txt .  The string read will be put to the string.

  • char str[] is the char array we will store the string we read.
  • FILE *f is the file pointer we will use to read the string.

Read From File Whole Line

Read From File Whole Line

We will store the code above with the file name fgets.c and we will compile with the following command.

AND  run the created fgets executable like below.

Read From File Whole Line

Read From File Whole Line

Read From Line Specified Number Of Bytes or Size

In this example, we will specify the string size we want to read. The size value will be provided as the second parameter of the fgets()  function. In this example, we will read 300 characters from the given file to the str char array.

RSS
FACEBOOK
FACEBOOK
PINTEREST
PINTEREST
LINKEDIN
INSTAGRAM

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)