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
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;
}
int main(int argc, char *argv[])
Here int argc is the number of command line arguments. char *argv[] is the array holding the 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)
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
After compiling the program it can be executed as,
./main README.md main.c
It will print the content of both README.md and main.c to the standard output (i.e Terminal Screen).
Top comments (0)