Linux C implements the CP function

Source: Internet
Author: User


One: Background

Read the Unix/linux programming practice, followed by the book Code to achieve a copy of ordinary files, see after class exercises need to implement the copy between directories, so with this article, I initially implemented CP with more than 180 lines of code, and later felt that many places can be encapsulated, But in the end, the more the package reached more than 200 lines, tonight decisively again encapsulated, trimmed the code about 170 lines, more than the answer after the lesson to be simpler. The CP can be used to copy the normal files, copy to the specified directory, and direct copy of the directory and other functions.


Second: Ideas

Copy between Directories I think the main function is the path of the assembly, the path to handle the problem, it is very simple. For example/root/a.txt Copy to/tmp, then as long as the incoming/root/a.txt and/tmp/a.txt can, then the key is/TMP and a.txt assembly, in the copy to the/tmp/you can also first determine whether the target has the same file exists. If there is a prompt user to overwrite (this feature I have not yet done). Here is mainly the string processing function used more, there is a function return is worth a difficulty (the next post describes the function return value).


Three: Realize

#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <unistd.h> #include < stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <dirent.h > #include  <libgen.h> #define  buffersize 4096#define copymode 0644char * Deal_path (char *,char *); char *deal_path1 (char *,struct dirent *); int is_ File (char *); Char *deal_with (char *,char *); Void oops (char *,char *); int  exists (char *); VOID&NBSP;DO_CP (char *,char *); Int main (int argc,char *argv []) {        char answer[10];         char c;        //setting buf         struct stat filebuf1;        struct  stat filebuf2;        struct stat tmpbuf;         char *filename=null;        char *filename2=null ;        struct dirent  *dirname;         dir *dir_ptr;        //Judgment Parameters                  if (argc != &NBSP;3) {                 fprintf (stderr, "usage: %s source destination\n", *ARGV);                 exit (1);         }        //determine if the source and destination files are equal          if (strcmp (argv[1],argv[2])  == 0)         {                 fprintf (stderr, "no copy source file  equal dest file\n ");                 exit (1);        }         //whether the test file can access         if (Access (ARGV[2],F_OK)  ==  0) {                // Ask if the file can be overwritten                  printf ("can you ovver the file  (y/n):");        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SCANF ("%9s", &answer);                  while ((C = getchar ())  != eof && c  !=  ' \ n ');        }         //Judging the user's input         if (*answer !=  ' y '  & & *answer !=  ' Y ') {                 fprintf (stderr, "The dst file exists,don ' t over\n");                 exit (1);         }        //to determine if the target is a directory          stat (ARGV[2],&AMP;FILEBUF2);         stat (ARGV[1],&AMP;FILEBUF1);         if (! S_isdir (Filebuf1.st_mode)) {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp;          if (S_isdir (filebuf2.st_mode))                           filename = deal_path (argv[2],argv[1]);                 else                         filename  = argv[2];        //      printf ("% s\n ", filename);                &NBSP;DO_CP (Argv[1],filename);                 free (filename);              }                      else{                 if (S_ISDIR ( Filebuf2.st_mode))                  if ((Dir_ptr = opendir (argv[1))  == null)                          sprintf ( "StdErr", "Can ' t open dir %s\n", argv[1]);                 else                         while ((Dirname=readdir (dir _PTR)  != null) {                                          filename = deal_path (Argv[1],dirname->d_name);                                          if (Is_file (filename)) {                                                  filename2 = deal_with ( FILENAME,ARGV[2]);                                                   do_cp (filename,filename2);                                                   free (filename);                                                   free (filename2);                                          }else{                                                   free (filename);                                                   continue;                                          }                                  }                         }                 closedir (dir_ptr); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}VOID&NBSP;DO_CP (char &NBSP;*PATH1,CHAR&NBSP;*PATH2) {        int in_fd,out_fd,n_chars;         char buf[BUFFERSIZE];         if ((In_fd = open (path1,o_rdonly))  == -1)                  oops ("Cannot open", path1);         if ((Out_fd = open (path2,o_wronly| O_creat,copymode)  == -1)                  oops ("Cannot create", path2);         //begins reading         while (n_chars  = read (in_fd,buf,buffersize))  > 0)                  if (Write (out_fd,buf,n_chars)  != n_chars)                  oops ("Write error  to ", path2);         //determine if the final write          if (n_chars == -1)                  oops ("Read error from,path1", "");                          //determine if the last write         if (n_chars == -1)          &nbSp;       oops ("Read error from,path1", "");         //Close File         if (Close (IN_FD)  ==  -1| | Close (OUT_FD)  == -1)                  oops ("Error closing files", "");} Void oops (CHAR&NBSP;*S1,CHAR&NBSP;*S2) {        fprintf (stderr, " error:%s  ", S1);         perror (S2);         exit (1);} Int exists (char *filename) {        return access ( FILENAME,F_OK);} Int is_file (Char *filename) {        struct stat  Filebuf;        stat (FILENAME,&AMP;FILEBUF);         if (S_Isreg (Filebuf.st_mode))                  return 1;        else                 return 0;} Char *deal_with (char *filename,char *filename2) {         char *file=NULL;;         if (file =  (char *) malloc (strlen (basename ( filename)) +strlen (filename2) +3)  == null)                  perror ("Malloc error");                          Else{                if ( Filename2[strlen (filename2) -1] == ‘ /') {                         strcpy (file,filename2);                         strcat ( File,basename (filename));                 }else{                         strcpy (file,filename2);                          strcat (file, "/");                         strcat (file,basename (filename));                      }         }        return file;} Char *deal_path (char *file,char *file2) {        char  *filename=null;        if ((filename =  (char *) malloc (strlen (file) +strlen (file2) +3)  == null)                                   perror ("Malloc erro:");         else {        if (File[strlen (file) -1] ==  '/') {                          strcpy (filename,file);                          strcat (filename,file2);         }else{                          strcpy (Filename,file);                         strcat ( FileName, "/");                         strcat (Filename,file2);                 }        }         return filename;} The most common use of this deal_path function, this function will determine the difference between the/tmp/ /tmp, will eventually be given to the two parameters to merge into a fileThe path creates and writes the content to be copied. 

Four: summary

C Language Foundation is very important, recently in the C expert programming, C and pointers, feeling very deep inside a lot of C language details I do not know. And I know very little about the structure's byte alignment in Linux C programming. Later, the blog will be used to record relevant content to deepen their understanding of these content.

This article is from the "Focus on Linux" blog, so be sure to keep this source http://forlinux.blog.51cto.com/8001278/1530293

Linux C implements the CP function

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.