1 /**
2  * Copyright (c) 2005 PCMan <pcman.tw@gmail.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18 
19 #include "fileutil.h"
20 #include <unistd.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 
copyfile(const char * src,const char * dest,int overwrite)26 int copyfile(const char* src, const char* dest, int overwrite)
27 {
28 	int fdsrc;
29 	int fddest;
30 	char buf[4096];
31 	size_t rlen = 0;
32 	struct stat file_st;
33 	mode_t fmode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
34 
35 	if( -1 != (fdsrc = open(src, O_RDONLY)) )
36 	{
37 		/* File already exists */
38 		if( !overwrite && !access( dest, F_OK) )
39 			return 0;
40 		if( -1 != (fddest = open(dest,
41 		                         O_CREAT | O_WRONLY | O_TRUNC,
42 					 fmode) ) )
43 		{
44 			while( (rlen = read( fdsrc, buf, sizeof(buf) )) )
45 				rlen = write( fddest, buf, rlen );
46 			close(fddest);
47 			close(fdsrc);
48 
49 			stat(src, &file_st);
50 			chmod(dest, file_st.st_mode);
51 			return 0;
52 		}
53 		close(fdsrc);
54 	}
55 	return -1;
56 }
57 
58