Linux system programming: Write a cp command by yourself, linuxcp

Source: Internet
Author: User

Linux system programming: Write a cp command by yourself, linuxcp

Basic usage of the cp command: the target file of the cp source file

If the target file does not exist, create it. If yes, overwrite it.

Implementing a cp command is actually an operation to read and write files:

For source files: read all the content to the cache. The read function is used.

For the target file: write all the content in the cache to the target file. The function creat is used.

1/* ============================================== =========================================== 2 * Copyright (C) 2018. all rights reserved. 3*4 * file name: mycp. c 5 * Creator: ghostwu (Wu Hua) 6 * creation Date: July 7 * description: cp command to write 8*9 ==================================================== =============================== */10 11 # include <stdio. h> 12 # include <stdlib. h> 13 # include <sys/types. h> 14 # include <sys/stat. h> 15 # include <fcntl. h> 16 # include <unistd. H> 1718 # define COPYMODE 064419 # define BUF 409620 21 int main (int argc, char * argv []) 22 {23 if (argc! = 3) {24 printf ("usage: % s source destination \ n", argv [0]); 25 exit (-1 ); 26} 27 28 int in_fd =-1, out_fd =-1; 29 30 if (in_fd = open (argv [1], O_RDONLY) =-1) {31 perror ("file open"); 32 exit (-1); 33} 34 35 if (out_fd = creat (argv [2], COPYMODE )) =-1) {36 perror ("file copy"); 37 exit (-1); 38} 39 40 char n_chars [BUF]; 41 int len = 0; 42 43 while (len = read (in_fd, n_chars, size Of (n_chars)> 0) {44 if (write (out_fd, n_chars, len )! = Len) {45 printf ("file: % s copy error \ n", argv [2]); 46 exit (-1 ); 47} 48} 49 if (len =-1) {50 printf ("read % s file error \ n", argv [1]); 51 exit (-1 ); 52} 53 54 if (close (in_fd) =-1) {55 printf ("failed to close file % s \ n", argv [1]); 56 exit (-1); 57} 58 if (close (out_fd) =-1) {59 printf ("failed to close file % s \ n ", argv [2]); 60 exit (-1); 61} 62 63 return 0; 64}View 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.