C fgets() Function: How to Fetch Strings from Anywhere!

fgets cC is a very powerful programming language, widely used by professional programmers to develop complex and very useful software programs. The language has a very structured syntax making it relatively easy to learn and use. It also provides great constructs to manipulate files and strings. In this tutorial, we’ll walk you through one of the important string usage functions – fgets() – that lets you read or fetch strings from files.

This is an intermediate level tutorial (i.e. we assume you have some basic exposure to C). Though we’ll walk you through the basics, if you’re new to C programming, we do recommend you first try out this beginner course on C programming.

What Does the fgets Function Do in C Language ?

fgets() is one of the file I/O (input / output) functions in C language and part of the “stiod.h” library. The name itself gives you a hint towards its functionality. The “f” at the start indicates this a file operation. The “get” indicates this function is used to “get” something from a file. The “s” indicates that this function fetches a string from a file.  You can of course also use this to read a string from the standard input device that is your keyboard. Before we get into the details of fgets(), let’s do a quick recap on ‘strings’ in C (you could also learn about strings in C in this basic C course).

In C, any textual data you want to manipulate is called a ‘string’. While specifying a string, you have to place the text between double quotation marks. Internally, C language stores the string as an array of characters. For example, the syntax to store a string of 6 characters would be something like this

#include “stdio.h”;
char string_example[7];
string_example=”Hello”;

Note that in C, arrays begin at index zero. String arrays always have an extra character ‘\n’ at the end, to mark the end of the string. You can say it’s similar to a period at the end of a sentence. Though this string terminator is not printed or show, it still takes up a space internally. Therefore, you always need to allocate an extra memory space for it in your array.

How to Use fgets()

Here is the syntax for fgets()  to read a string from a file

char *fgets(char *str, int size, file* file);

Let’s take a better look at the parameters here

  •  str– This is a pointer to the string or array of characters where you want to save the string after you read it.
  • size– This is the total number of characters you want to read. Remember to include the ending null character.

  • file– This is the pointer to the File object from where you want to read the string.

If you want to read the string from your keyboard, then just use ‘stdin’ instead of the file pointer, like this

 fgets(pString,size,stdin);

“Stdin” is the name C internally uses for the standard input ie the keyboard. Yes, fancy name! Let’s try this out in a simple program to see how it works.

Example 1: fgets() Reads a String through the Keyboard

#include <stdio.h>
int main()
{
 char name[10];
 printf("Who are you? \n");
 fgets(name,10,stdin);
 printf("Good to meet you, %s.\n",name);
 return(0);
}

Running this program would show the following on your screen:

Who are you?
You enter a name on your keyboard. Example: Benny Samuel
Good to meet you, Benny Sam.

What happened here? Why did it print just half of your name? Well, only nine characters, to be precise, are displayed on your screen. Did you wonder why only nine? That’s because there is room only for 9 characters + the null terminator in our string “name[10]”. If the fgets() were to read 10 characters instead of 9 then the program will malfunction  due to buffer overflow.

When should You Use fgets() versus scanf()

Strings are used in C programming to hold all types of text input.  For instance, if you want to enter your name, you have to use a string. In the basic C course, you would have learnt about scanf(). Both scanf() and fgets() are used to get or read string inputs. How do you differentiate when to use which one? Here’s how you can decide

1. Are you reading the text string from keyboard or a file? If you want to read from a file, you have to use fgets(). To read from a keyboard, you can use either.

2. Does your string have spaces in it? For example if you’re entering your name “John Smith” with a space between the first name and family name, scanf() will simply exit ie stop reading further once it hits the space. So scanf() will end up reading just “John”. For such cases, you’re better off using fgets().

Example 2: How to read (and then print out the content) from a file

Now lets take a look at an example with fgets() reading from a file.

#include <stdio.h>
int main()
{
  FILE *fp;
  char str[60];
 /* opening file for reading */
 fp = fopen("file.txt" , "r");
 if(fp == NULL) {
   perror("Error opening file");
   return(-1);
 }
 if( fgets (str, 60, fp)!=NULL ) {
   /* writing content to stdout */
   puts(str);
 }
 fclose(fp);
 return(0);
}

Can you guess what this program will do? Here’s a brief walk through the main statements:

 fp = fopen("file.txt" , "r");  

Opens the file in read mode and returns the pointer to the file and stores it in the variable fp.

 if( fgets (str, 60, fp)!=NULL );

fgets() reads  60 characters from the file and stores it in the string array. It returns NULL if it has reached the end of the file.Check to make sure fgets() actually read the string and has returned a non-zero value.

 puts(str);

Prints the content of str array on to the screen.

 fclose(fp);

Book keeping! Close the file.

We hope these examples show you how you can use fgets() to get or fetch strings that you want, from a file, or from the keyboard. C programming is fun even for beginners to take up. As always, remember that practice makes perfect. Do hone your C skills with lots of hands on programming. You can check out this C course that has tons of examples.

Who knows, you may very soon be developing your own iPhone app in C (here’s a course to help get you started!).