One string parsing function you should be aware of is fgets c, which lets you access formatted strings stored as files. This C language guide assumes you already have past exposure to its overall structure and is best suited for intermediate programmers.

Code on laptop screen

C is what you’d call the parent language of computing due to its ubiquitous reputation among professional developers. Without a doubt, many complex programs were built on the C architecture, thanks to its clean syntax and diverse use of constructs to manipulate all kinds of data. 

If you are wondering about what separates C and C++ libraries, continue reading this article to compare them by performance. It will discuss at length the components each has and which approach is ideal for handling structured data. 

C Programming For Beginners

Last Updated August 2019

  • 76 lectures
  • All Levels
4.4 (4,119)

Learn C in ten easy steps on Windows, Mac OS X or Linux | By Huw Collingbourne

Explore Course

Reading Strings with Fgets C from a File

By now, you’ve probably heard of I/O functions that transmit information from a computer system to an outside device. This term typically refers to user interactions with data through a library of modules that operate on different file types. 

Fgets() is one of them. It gets something from a file and copies it to the terminal, just like a web scraper or any other data extraction tool. Fgets() reads or fetches a string from a chosen file. It can also read a string taken from your keyboard input. 

Before you dig deeper into the fgets function, remember the correct syntax for strings in C: They have double quotes and are treated as an array of characters. A C array starts at the zero index and marks the end with \n: 

//Writing a string
#include “stdio.h”;

char string_example[int] = “string”;

demo_string = “Hello world!”;

//Declaring an array
type arrayName [ arraySize ];

double balance[int] = { list of values };

To define fgets() in C, use the syntax here:

char *fgets(char *str, int size, file* file);
  1. The char str variable stores a string or an array of fixed length after it has been read. 
  2. The size parameter specifies the number of characters to read, ending with the null character. 
  3. The file parameter points to a File object and starts at the position you want to read.

On the other hand, if you prefer to read from keyboard, then use the standard format:

fgets(pString, size, stdin); 

How to Read a String from Keyboard in C

The ability to read a string from Keyboard in C is quite important whenever you need to parse the string a user enters into a form field. It is where a login page saves the username and password. Let’s walk through this program to see what it does:

Int main() 
//declare a pointer
    char word[str limit];

//read input of unknown length
    fgets(word, sizeof(word), stdin);

The “str limit” is arbitrary; it only estimates the largest string possible and prevents a buffer overflow in case the number is exceeded. The fgets function is supposed to read the strings input by the user of varying lengths. It registers words typed into a keyboard with the stidin term. 

Top courses in C (programming language)

C Programming For Beginners – Master the C Language
Tim Buchalka’s Learn Programming Academy, Jason Fedin
4.3 (28,991)
Advanced C Programming Course
Tim Buchalka’s Learn Programming Academy, Jason Fedin
4.4 (3,136)
Linked Lists with C
Portfolio Courses
4.8 (53)

More C (programming language) Courses

When is it appropriate to use scanf() as opposed to fgets()?

Although both fgets() and scanf() can read string inputs, it would be better to pick one over the other in some scenarios. For reading from open files, you are required to declare fgets() whereas reading from keyboard opens up to either option. 

Scanf() will immediately exit a string the moment it hits a space so its utility is limited to single, continuous strings. On the contrary, fgets() reads the whole line from a file stream, then copies the bytes via a null terminating string to the str buffer. 

Let’s demonstrate with one final program that reads from a string array:

#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");

    if( fgets (str, 60, fp)!=NULL ) {
       /* writing content to stdout */


What the program does is open a file in read mode using fp = fopen(“file.txt” , “r”); After that, it returns a pointer to said file by storing it in the fp variable. It is wrapped inside an int main() to produce an integer (0 or 1) after the last line is executed. 

The if conditional has fgets (str, 60, fp)!=NULL to ensure it only reads up to 60 characters before storing it into a string array. Otherwise, the NULL value is returned to indicate the EOF. The puts(str) checks whether fgets() managed to read the string. 

The last step is to print the str array output onto the screen before it closes the file with fclose(fp);

For additional resources on C programming, you can preview our selection of courses ranging from those that are beginner-friendly to the most popular ones available. 

Frequently Asked Questions

What does fgets do in C?

fgets() is a C library function that reads characters from the target stream and proceeds to store the information in a str-pointed string. fgets C will keep going until it lands on a newline character or the end of a file is reached. 

The syntax of this function:

char *fgets(char *str, int n, File *stream)
  1. The fgets str points to the character array, which will be read until it runs through n-1 characters. 
  2. The letter n recalls the largest number of characters for the function to read. The length of this array is often set as the n value. 
  3. The stream is a File object pointer for locating the stream to be read by fgets. 

It so happens that the only reason a null pointer is returned is to signal an End-of-File encounter in which no characters were ever read. If an error occurs in the process, you can expect a null pointer to return as well. 

What is the difference between fgets and gets in C?

There are several factors that set fgets() and gets() apart. First of all, fgets() reads a single line from an input stream while being mindful of any constraints, such as the max length or device reference. 

It readily checks the boundaries of the specified array and stops on a new line. In fact, the number of characters cannot exceed the fgets size or else it won’t print out. It serves as a safer version of gets() by limiting the input size to avoid a potential buffer overflow. 

The gets function differs in that it reads characters from a standard input and stores them into str memory, terminating once it reaches the EOD. The syntax for gets() is: char * gets ( char * str ); which scans a string of user input until it cannot find a newline. 

The problem is that gets() is prone to triggering overflow errors. This is caused by writing data beyond the allotted memory limit. gets has no way to check for array bounds, so it must override another variable’s value. 

What can I use instead of fgets in C?

A possible alternative to fgets would be the getline() function. It is written in the form: str.getline(buffer, size, stdin). The buffer tracks the first position of a character, the size is a variable address that holds the input buffer, and stdin deals with the file handle. 

This function behaves similarly to fgets by calling str.erase() and extracting chars from the input to place inside str. It also stops at the EOD and has a limit of str.max_size() to confine the string read between the bounds. 

A second substitute for fgets is to use a char[ ] in the format: char buffer[Max_Size]. What it does is sidestep calling fgets to build a string from the buffer, therefore creating a space in which to store the substring. 

Page Last Updated: December 2021