C (programming language)

C program to read data from file using fgets() function


The fgets() function in C is a versatile tool for reading data from text files. It offers a safer and more controlled approach compared to other file reading functions like gets(). In this guide, we’ll explore how to use fgets() to effectively read data from files in C programs.

Key Concepts

  • fgets() Syntax: Cchar *fgets(char *str, int size, FILE *stream);
    • str: The character array where the read string will be stored.
    • size: The maximum number of characters to read, including the null terminator.
    • stream: The file pointer pointing to the open file.
  • Return Value:
    • Returns a pointer to the str if successful.
    • Returns NULL if an error occurs or the end of the file is reached.

Steps to Read Data from a File

  1. Include Necessary Header: C#include <stdio.h>
  2. Open the File: CFILE *fp = fopen("filename.txt", "r");
    • Replace “filename.txt” with the actual file name.
    • “r” mode opens the file for reading.
  3. Check for File Opening Errors: Cif (fp == NULL) { printf("Error opening file!\n"); return 1; // Indicate error }
  4. Read Data Line by Line using fgets(): Cchar buffer[100]; // Adjust buffer size as needed while (fgets(buffer, sizeof(buffer), fp) != NULL) { // Process the read line (e.g., print it) printf("%s", buffer); }
  5. Close the File: Cfclose(fp);

Example Code


#include <stdio.h>

int main() {
    FILE *fp = fopen("myfile.txt", "r");

    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;

    char line[50];

    while (fgets(line, sizeof(line), fp) != NULL) {
        printf("%s", line);


    return 0;

Key Points to Remember

  • fgets() preserves the newline character (\n) if present in the file.
  • It stops reading at size - 1 characters or when it encounters a newline, whichever comes first.
  • Always check the return value of fgets() to handle errors or the end of the file.
  • Choose an appropriate buffer size to accommodate the expected line lengths.
  • Close the file using fclose() when finished to release resources.

Additional Notes

  • Consider using ferror() to check for errors during file operations.
  • Use feof() to determine if the end of the file has been reached.
  • For more complex file handling tasks, explore other file I/O functions in C.


Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

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

Back to top button