Almost certainly, 80% of programmers have used cat programs. It is a command used in Linux to connect multiple files. It will be a good job to simulate and write such a small program, cat supports two methods: parameter and parameter-free,
If there is no parameter, standard input and output will be used for implementation. If there is a parameter, the file link specified in the parameter will be displayed on the standard display. What is my first step? Read characters from a specified input stream.
The code displayed on the specified output stream is roughly as follows:
// Copy the content from SRC to destint filecopy (File * SRC, file * DEST) {int C; while (C = GETC (SRC ))! = EOF) putc (C, DEST); Return C ;}
The code above clearly not only copies the content to the standard output, but also copies any file. The following implementation is relatively simple:
// Mainint main (INT argc, char * argv []) {printf ("Ctrl + C Exit \ n"); If (argc = 1) {// if there are no parameters, obtain the input from the keyboard and display it in the screen filecopy (stdin, stdout);} else {char * input; // file * inf to be connected; // int COUNT = 0 for the file to be connected; // number of successful connections while (-- argc> 0) {input = argv [argc]; If (INF = fopen (input, "R") = NULL) {// if a file cannot be opened, skip printf ("\ ncan't open % s \ n", input); continue ;} count ++; filecopy (INF, stdout); fclose (INF) ;}printf ("** cat % d file **", count); getchar (); return 0 ;}}
It's easy to run this cat. Cat or cat f1.c f2.o
If you are interested, you can download the complete program here. Source code