In this blog post I am going to explain how to create your own cat command :-) . we can do it with a simple 'C' program with command line arguments. We write a simple program with basic file operations and command line arguments.
Step 1: Open your favorite text editor
Step 2: Copy the following code to your text editor
Step 4: Go to file location
Example: cd /home/senan/myprograms
Step 5: Compile the file
cc -o mycat mycat.c in your terminal
Step 6: run the program by
./mycat /etc/passwd or you can copy the file to /bin in order to avoid the ./ usage. That is
sudo cp mycat /bin
Step 7: :-)
Step 1: Open your favorite text editor
Step 2: Copy the following code to your text editor
/* @ @ File Name : mycat.c @ Author : Prabhendu V Senan @ Description : This is a simple C program to display the contents of a file(exactly like the "cat" command in Linux) @ @ */ #includeStep 3: Save the file(ex: mycat.c)#include #define INVALID_ARG_LIST 2 int main(int argc,char *argv[]) { FILE *pfile = NULL; char *file_name = NULL; int fchars = 0; int arg_index = 0; /* If no file name is given then exit the program */ if(argc < INVALID_ARG_LIST) { printf("Correct usage is: mycat \n"); exit(1); } for(arg_index = 1; arg_index < argc; arg_index++) { file_name = argv[arg_index]; /* Try to open the file. If failed,Exit the program */ if(!(pfile = fopen(file_name,"r"))) { printf("Unable to open file!!\nEither the file doesn't exist or pemission denied\n"); exit(1); } while((fchars = fgetc(pfile)) != EOF) { putchar(fchars); } fclose(pfile); pfile = NULL; file_name = NULL; fchars = 0; } return 0; }
Step 4: Go to file location
Example: cd /home/senan/myprograms
Step 5: Compile the file
cc -o mycat mycat.c in your terminal
Step 6: run the program by
./mycat /etc/passwd or you can copy the file to /bin in order to avoid the ./ usage. That is
sudo cp mycat /bin
Step 7: :-)