C program to read a text file

Last updated on 09th February 2015

This is a C program that reads a text file and displays its content on to screen.

Assumptions

  1. The name of the file to be read is passed as an argument when the program is executed.

Key Steps

  1. Validates if a filename has been entered, if not display error message and exit the program.
  2. Open the file for read only, using fopen function, and store the return value to a file pointer variable.
  3. If file opened successfully then continue next steps, otherwise display error message and exit.
  4. Using fgetc function, read the characters from the file one by one until End Of File.
  5. Print the character that is read to standard output, which is the display screen.

Program Source

(Filename: read-file.c)

/***************************************************
 * This program reads a file specified by the user *
 * as a command line argument and display the      *
 * contents of the file on screen.                 *
 ***************************************************/

#include <stdio.h>

int main(int argc, char *argv[])
{
 FILE *fp;
 char *filename;
 char ch;

  // Check if a filename has been specified in the command
  if (argc < 2)
   {
        printf("Missing Filename\n");
        return(1);
   }
   else
  {
        filename = argv[1];
        printf("Filename : %s\n", filename);
   }

   // Open file in read-only mode
   fp = fopen(filename,"r");

   // If file opened successfully, then print the contents
   if ( fp )
      {
        printf("File contents:\n");
        while ( (ch = fgetc(fp)) != EOF )
           {
                printf("%c",ch);
           }

       }
   else
      {
         printf("Failed to open the file\n");
        }

return(0);
}

Program Input

(Input File : myfile.txt)

The quick brown fox jumps over the lazy dog.
Pack my box with five dozen liquor jugs.

Compile and Run

Compile the program and run the executable with the input filename as argument

./read-file.exe myfile.txt 

Program Output

Filename : myfile.txt
File contents:
The quick brown fox jumps over the lazy dog.
Pack my box with five dozen liquor jugs.

Also Read


Post a comment

Comments

Görkem | November 15, 2020 10:50 PM |

Thank you very much. I was searching for this

micahel taulava | August 17, 2017 7:02 AM |

Not working. it give missing file immediately.