View Single Post
Old 10 August 2014, 19:46   #6
alkis
Registered User
 
Join Date: Dec 2010
Location: Athens/Greece
Age: 53
Posts: 719
Well, I was bored...so here is a C implementation.
if return value >=0 then no errors occured. (returns the bytes copied on normal execution)
Otherwise, returns the errors in the defines.
Note: lightly tested (on KS3.1 and on KS1.3), seems to work though.

Code:
#include <exec/types.h>
#include <dos/dos.h>
#include <proto/exec.h>
#include <proto/dos.h>


#define FILECOPY_DEFAULT_BUFFERSIZE	(32768)
#define FILECOPY_SOURCE_FILE_ERROR	(-1)
#define FILECOPY_DESTINATION_FILE_ERROR	(-2)
#define FILECOPY_BUFFER_MEMORY_ERROR	(-3)
#define FILECOPY_READ_WRITE_ERROR	(-4)


LONG FileCopy(STRPTR from, STRPTR to)
{
	LONG readBytes, writtenBytes;
	LONG totalBytes = 0;
	BPTR fromBPTR, toBPTR;
	void *buffer;
	LONG buflen = FILECOPY_DEFAULT_BUFFERSIZE;



	fromBPTR = Open(from, MODE_OLDFILE);
	if (!fromBPTR) {
		//PrintFault(IoErr(),"Open()");	//needs >=KS2.0
		return FILECOPY_SOURCE_FILE_ERROR;
	}
	toBPTR = Open(to, MODE_NEWFILE);		// !!!no overwrite check!!!
	if (!toBPTR) {
		//PrintFault(IoErr(),"Open2()");	//needs >=KS2.0
		Close(fromBPTR);
		return FILECOPY_DESTINATION_FILE_ERROR;
	}

	while (!(buffer = AllocMem(buflen, MEMF_ANY))) {
		buflen >>= 1;
		if (buflen < 1024) { //if there not even a Kb free, shut it down, return error.
			Close(fromBPTR);
			Close(toBPTR);
			return FILECOPY_BUFFER_MEMORY_ERROR;
		}
	}

	while ((readBytes = Read(fromBPTR, buffer, buflen)) > 0) {
		writtenBytes = Write(toBPTR, buffer, readBytes);
		if (writtenBytes == -1 || writtenBytes != readBytes) {
			//PrintFault(IoErr(),"Write()");	//needs >=KS2.0
			break;
		}
		totalBytes += writtenBytes;
	}

	Close(fromBPTR);
	Close(toBPTR);
	FreeMem(buffer, buflen);

	if (readBytes) {
		DeleteFile(to);	//Delete the destination file on read/write error
		return FILECOPY_READ_WRITE_ERROR;
	}
	return totalBytes;
}

Last edited by alkis; 10 August 2014 at 19:51. Reason: Mention KS1.3 combartibility
alkis is offline  
 
Page generated in 0.04263 seconds with 11 queries