DEV Community

Cover image for Building Linux Commands From Scratch 🐧 cat Command
Suraj Kareppagol
Suraj Kareppagol

Posted on

Building Linux Commands From Scratch 🐧 cat Command

I am “Building Linux Commands From Scratch With C/C++”. The main reason behind this is to get some experience around C/C++, also i am a fan of Linux and it’s ecosystem.


Command ➡️ cat

cat commands allows us to concatenate files and print on the standard output.

cat README.md
Enter fullscreen mode Exit fullscreen mode

This command prints the content of README.md on the standard output.

#include <stdio.h>

int main(int argc, char *argv[])
{
  char character;

  if (argc > 1)
  {
    for (int i = 1; i < argc; i++)
    {
      FILE *file = fopen(argv[i], "r");

      while ((character = fgetc(file)) != EOF)
        printf("%c", character);

      fclose(file);
    }
  }

  return 0;
}
Enter fullscreen mode Exit fullscreen mode
int main(int argc, char *argv[])
Enter fullscreen mode Exit fullscreen mode

Here int argc is the number of command line arguments. char *argv[] is the array holding the command line arguments.

For Command Line Arguments

Since the file name of the program is the first argument passed it starts reading files from index 1, a for loop is used from 1 to argc.

Then a FILE pointer is created and file is opened in read mode. Then a while loop is used to read each single character from the file.

while ((character = fgetc(file)) != EOF)
Enter fullscreen mode Exit fullscreen mode

Loop Until character Is Not EOF

The loop continues until EOF (End Of File) is not encountered. Once EOF is encountered loop stops and the file is closed. This will be repeated for other files.

gcc main.c -o main
Enter fullscreen mode Exit fullscreen mode

After compiling the program it can be executed as,

./main README.md main.c
Enter fullscreen mode Exit fullscreen mode

It will print the content of both README.md and main.c to the standard output (i.e Terminal Screen).

Top comments (0)