C Language Simulation of cat programs in Linux

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.