How to use fgets in C Programming, you should know

The fgets function reads characters from the specified stream and stores them in the character array. It reads only n-1 characters, where n is the specified number of characters.

It stops the reading when reading a newline character or (n-1)th character, or encountering end-of-file (EOF). The good thing is that it writes a null character just after writing the last character into the array.

In this article, I will explain to you, how to read the character array or string from the given file using fgets in C programming with examples.

Note: You have to include the stdio.h ( header file) before using fgets in C Programming.

Syntax of fgets:

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

Where,

s: Pointer to a character array with a minimum size of n bytes.
n: Maximum number of characters to be copied into s  (including the terminating null character).
stream: Input stream (file pointer of an opened file).

Note: stdin can be used as an argument to read from the standard input.

 

Return value of fgets():

On success, the fgets function returns the string (same s parameter). On error return a null pointer.

Note: If end-of-file is encountered and no characters have been read into the “s” (character array), the contents of the “s” remain unchanged and a null pointer is returned.

 

Example code to explain the working of fgets in C,

In this example, I am reading a file “aticleworld.txt” using the c fgets which contains the string “I am using fgets.”.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char readFileData[MAX_SIZE] = {0};

    //open the file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }

    //Read file using fgets
    if(fgets(readFileData,MAX_SIZE,fp) == NULL)
    {
        printf("Error in reading the file\n");
        //close the file
        fclose(fp);
        exit(1);
    }

    //Display read data
    puts(readFileData);

    //close the file
    fclose(fp);

    printf("Read file successfully\n");

    return 0;
}

Output:

fgets in c

 

Code Analysis:

In the above c fgets example, first, we opened the already created text (“aticleworld.txt”) file in reading mode and get the file pointer. Using the if condition I am verifying that file is opened successfully or not.

//open the file
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
    printf("Error in creating the file\n");
    exit(1);
}

 

After opening the file successfully, I have used c fgets to read the character array from the file (“aticleworld.txt”). I have also used the if condition to check whether fgets reads a character array without error or not.

//Read file using fgets
if(fgets(readFileData,MAX_SIZE,fp) == NULL)
{
    printf("Error in reading the file\n");
    //close the file
    fclose(fp);
    exit(1);
}

 

In the last, I have used puts to display reads character array on console and fclose to close the opened file.

//Display read data
puts(readFileData);

//close the file
fclose(fp);

printf("Read file successfully\n");

 

You can check this Article.

Difference between fgets and gets in C:

There is the following difference between the fputs and puts in C.

1. The fgets function takes three arguments first is the pointer to the character array second maximum number of characters to be read (including terminating null character) and third is an input stream (file pointer).

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

 

In another hand, gets takes only one argument pointer to a character array.

char * gets ( char * s);

 

2. fgets function can read from any specified file stream while gets only read from stdin.

 

Consider the example:

In the below example, I have created a character array of size 10.  Using the gets function I am reading the stdin and storing all read characters in the character array.  If I give the input more than 10 characters then the gets function reads all characters and stores it in the character array, it is wrong because can cause a buffer overflow.
#include <stdio.h>

#define ARRAY_SIZE 10

int main()
{
    char buf[ARRAY_SIZE];

    printf("Enter a string: ");
    gets(buf);
    printf("string is: %s\n",buf);

    return 0;
}

Output:

gets is risky in C

 

Besides that, if you will use the C fgets function. it only reads 9 characters and copies into the character array. So it avoids the risk of buffer overflow.
#include <stdio.h>

#define ARRAY_SIZE 10

int main()
{
    char buf[ARRAY_SIZE];

    printf("Enter a string: ");
    fgets(buf,ARRAY_SIZE,stdin);
    printf("string is: %s\n",buf);

    return 0;
}

Output:

fgets in c avoid risk

 

 

How to remove trailing newline characters from fgets input?

Below I am writing a C program to remove the trailing newline character from the fgets input

#include <stdio.h>
#include <string.h>

#define  BUFFER_SIZE 24

int main(void)
{
    char buf[BUFFER_SIZE];

    printf("Enter the data = ");

    if (fgets(buf, sizeof(buf), stdin) == NULL)
    {
        printf("Fail to read the input stream");
    }
    else
    {
        char *ptr = strchr(buf, '\n');
        if (ptr)
        {
            *ptr  = '\0';
        }
    }
    printf("Entered Data = %s\n",buf);

    return 0;
}

 

Explanation: In the above C program strchr()  (string function) replace the newline character in the string with ‘\0’ if it exists.

You can see the Article for more details, How to remove trailing newline character from fgets input?

 

 

Recommended Articles for you: