xref: /aosp_15_r20/external/mtools/copyfile.c (revision d5c9a868b113e0ec0db2f27bc2ce8a253e77c4b0)
1 /*  Copyright 1996-1999,2001,2002,2009 Alain Knaff.
2  *  This file is part of mtools.
3  *
4  *  Mtools 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 3 of the License, or
7  *  (at your option) any later version.
8  *
9  *  Mtools 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 Mtools.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 #include "sysincludes.h"
18 #include "msdos.h"
19 #include "mtools.h"
20 #include "file.h"
21 #include "llong.h"
22 
23 /*
24  * Copy the data from source to target
25  */
26 
copyfile(Stream_t * Source,Stream_t * Target)27 mt_off_t copyfile(Stream_t *Source, Stream_t *Target)
28 {
29 	char buffer[8*16384];
30 	mt_off_t pos;
31 	ssize_t ret;
32 	ssize_t retw;
33 
34 	if (!Source){
35 		fprintf(stderr,"Couldn't open source file\n");
36 		return -1;
37 	}
38 
39 	if (!Target){
40 		fprintf(stderr,"Couldn't open target file\n");
41 		return -1;
42 	}
43 
44 	pos = 0;
45 	while(1){
46 		ret = READS(Source, buffer, 8*16384);
47 		if (ret < 0 ){
48 			perror("file read");
49 			return -1;
50 		}
51 		if(!ret)
52 			break;
53 		if(got_signal)
54 			return -1;
55 		if (ret == 0)
56 			break;
57 		if ((retw = force_write(Target, buffer, (size_t) ret)) != ret){
58 			if(retw < 0 )
59 				perror("write in copy");
60 			else
61 				fprintf(stderr,
62 					"Short write %zd instead of %zd\n",
63 					retw, ret);
64 			if(errno == ENOSPC)
65 				got_signal = 1;
66 			return ret;
67 		}
68 		pos += ret;
69 	}
70 	return pos;
71 }
72