Skip to content
Laviyx Learn

Try

PPS Lab · Experiment 28

Display the contents of a file

CFilesJNTUH R22 · CS108ES

Aim

To write a C program that displays the contents of a text file on the standard output device (the screen). The file name is given as a command-line argument, or typed at the keyboard if no argument is given.

Algorithm

  1. If a command-line argument is given, use it as the file name. Otherwise ask the user to type the file name.
  2. Open the file in read mode ("r"). If fopen returns NULL, print an error and stop.
  3. Read one character with fgetc.
  4. While the character is not EOF, print it with putchar and read the next character.
  5. Close the file.

Program

C
#include <stdio.h>

int main(int argc, char *argv[]) {
    char name[100];
    const char *filename;

    if (argc >= 2) {
        filename = argv[1];
    } else {
        printf("Enter the file name: ");
        if (scanf("%99s", name) != 1) {
            printf("No file name given\n");
            return 1;
        }
        filename = name;
    }

    FILE *fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Cannot open file %s\n", filename);
        return 1;
    }

    int ch;
    while ((ch = fgetc(fp)) != EOF) {
        putchar(ch);
    }
    fclose(fp);
    return 0;
}

Output

File name as a command-line argument

Input file: poem.txt (Text)
Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
Output 1
$ ./a.out poem.txt
Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.

File name typed at the keyboard

Input file: marks.txt (Text)
Roll No  Name     Marks
101      Anil     78
102      Bhavya   91
103      Chandu   66
Output 2
Enter the file name: marks.txt
Roll No  Name     Marks
101      Anil     78
102      Bhavya   91
103      Chandu   66

File that does not exist

Output 3
$ ./a.out missing.txt
Cannot open file missing.txt

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The program copies the file to the screen one character at a time, so it works for a file of any length and keeps every space and line break as it is.

scanf("%99s", name) reads a name without spaces and stops after 99 characters, so it cannot overflow the 100-character array. To open a file whose name has spaces, give it as a command-line argument in quotes.

This is what the type command on Windows and the cat command on Linux do.

Common mistakes

  • Declaring ch as char. fgetc returns an int so that EOF can be told apart from real characters; with char the loop may stop early or never stop.

  • Not checking for NULL after fopen. If the file does not exist, reading from a NULL pointer crashes the program.

  • Using while (!feof(fp)) and then printing the character. feof becomes true only after a read has failed, so the last value (EOF) is printed as a strange extra character. Test the value returned by fgetc instead.

  • Using argv[1] when no argument was given. Check argc first; if argc is 1, argv[1] is NULL.

Viva questions

Try to answer each one aloud before you open it.

  • What is the standard output device, and how do you write to it in C?

    It is normally the screen. In C it is the stream stdout, used by printf, putchar and puts.

  • What is EOF?

    EOF (end of file) is a negative constant, usually −1, defined in stdio.h. Functions like fgetc return it when there is nothing more to read.

  • What is a FILE pointer?

    A pointer to a FILE structure, returned by fopen. It keeps the information C needs about an open file, such as the current position, and is passed to functions like fgetc and fclose.

  • What is the difference between fgetc and getchar?

    fgetc(fp) reads a character from the file fp. getchar() reads a character from the keyboard (standard input); it is the same as fgetc(stdin).

  • Why should a file be closed with fclose?

    fclose writes out any data still in the buffer and releases the file. A program can only have a limited number of files open at once.

Learn the concepts

All Programming for Problem Solving Lab experiments →