C program to read a file and display its contents

C Programming Language File Input/Output (Article) File Input/Output (Program)

129

Required knowledge

Basic Input Output, Do while loop, While loop, Pointers, File Handling

In the previous post, I explained how to use FILE pointer, fopen()fputs() and fclose() function to create and write data into file.

In this post, we will continue further and will learn various functions in C programming to read and display file contents on console.

How to read data from a file?

C programming supports four predefined functions fgetc()fgets()fscanf() and fread() to read data from file. These functions are defined in stdio.h header file.

fgetc() - Used to read single character from file.
fgets() - Used to read string from file.
fscanf() - Use this to read formatted input from file.
fread() - Read block of raw bytes from file. Used to read binary files.

Step by step descriptive logic to read a file and display file contents.

  • Open a file using fopen() function and store its reference in a FILE pointer say fPtr.

    You must open file in r(read) mode or atleast mode that support read access.

  • Read content from file using any of these functions fgetc()fgets()fscanf() or fread().
  • Finally, close the file using fclose(fPtr).

In this post I will explain how to read a file using fgetc() and fgets(). I will explain separately how to read formatted input and binary files.

How to read a file character by character using fgetc()?

int fgetc(FILE * stream);
  • The function accepts pointer to FILE type, source stream to read.
  • On each successful read it return character (ASCII value) read from stream and advance read position to next character.

    It returns a constant EOF (-1) on unsuccessful read or if there is no more content to read.

Suppose data/file1.txt contains

Hurray!!! I learned to create file in C programming. I also learned to write contents to file. Next, I will learn to read contents from file on Codeforwin. Happy coding ;)

Program:

/**
 * C program to read a file and display file contents character by character using fgetc() 
 */

#include <stdio.h>
#include <stdlib.h>


int main()
{
    /* File pointer to hold reference to our file */
    FILE * fPtr;

    char ch;


    /* 
     * Open file in r (read) mode. 
     * "data/file1.txt" is complete file path to read
     */
    fPtr = fopen("data/file1.txt", "r");


    /* fopen() return NULL if last operation was unsuccessful */
    if(fPtr == NULL)
    {
        /* Unable to open file hence exit */
        printf("Unable to open file.\n");
        printf("Please check whether file exists and you have read privilege.\n");
        exit(EXIT_FAILURE);
    }


    /* File open success message */
    printf("File opened successfully. Reading file contents character by character. \n\n");

    do 
    {
        /* Read single character from file */
        ch = fgetc(fPtr);

        /* Print character read on console */
        putchar(ch);

    } while(ch != EOF); /* Repeat this if last read character is not EOF */


    /* Done with this file, close file to release resource */
    fclose(fPtr);


    return 0;
}

Output:

File opened successfully. Reading file contents character by character.

Hurray!!! I learned to create file in C programming. I also learned to write contents to file. Next, I will learn to read contents from file on Codeforwin. Happy coding ;)

Explanation:

Program to read a file line by line using fgets()

Suppose data/file2.txt contains

Reading a file line by line.
--------------------------------------------
I love programming in C.
Learning programming on Codeforwin is easy.

/**
 * C program to read a file and display file contents line by line using fgets()
 */

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

#define BUFFER_SIZE 1000


int main()
{
    /* File pointer to hold reference to our file */
    FILE * fPtr;

    char buffer[BUFFER_SIZE];
    int totalRead = 0;


    /* 
     * Open file in r (read) mode. 
     * "data/file2.txt" is complete file path to read
     */
    fPtr = fopen("data/file2.txt", "r");


    /* fopen() return NULL if last operation was unsuccessful */
    if(fPtr == NULL)
    {
        /* Unable to open file hence exit */
        printf("Unable to open file.\n");
        printf("Please check whether file exists and you have read privilege.\n");
        exit(EXIT_FAILURE);
    }


    /* File open success message */
    printf("File opened successfully. Reading file contents line by line. \n\n");


    /* Repeat this until read line is not NULL */
    while(fgets(buffer, BUFFER_SIZE, fPtr) != NULL) 
    {
        /* Total character read count */
        totalRead = strlen(buffer);


        /*
         * Trim new line character from last if exists.
         */
        buffer[totalRead - 1] = buffer[totalRead - 1] == '\n' 
                                    ? '\0' 
                                    : buffer[totalRead - 1];


        /* Print line read on cosole*/
        printf("%s\n", buffer);

    } 


    /* Done with this file, close file to release resource */
    fclose(fPtr);


    return 0;
}

File opened successfully. Reading file contents line by line.

Reading a file line by line.
--------------------------------------------
I love programming in C.
Learning programming on Codeforwin is easy.

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.