CopyFile() Function

A function to copy a file from one location/name to another.

  • See function for explanation. Neither the function nor the test program checks to confirm the choice before proceeding. Be careful not to select an existing destination file, or it will be overwritten immediately! The function will fail if both the source and destination paths and filenames are the same. Paths are not necessary in all cases but are highly recommended.
filedialog "Open file to copy...", "*.*", toCopy$
if (toCopy$ = "") then
    goto [exit]
else
    filedialog "Save file as...", "*.*", copyTo$
    if (copyTo$ = "") then
        goto [exit]
    else
        fileCopied = CopyFile(toCopy$, copyTo$)
        n$ = word$("not .", abs(not(fileCopied)), ".")
        notice "File "; n$; "copied."
    end if
end if
 
[exit]
end
 
function CopyFile(fileToCopy$, copyToFile$)
    'If source and destination are not blank...
    if (not(fileToCopy$ = "") and not(copyToFile$ = "")) then
        'Open both files.
        open fileToCopy$ for input as #fileToCopy
        open copyToFile$ for output as #copyToFile
 
        'Get size of source file.
        ftcLen = lof(#fileToCopy)
 
        'Set the maximum chunk size to be the smaller
        'of the source file size or 4096. Modify the
        'value to adjust the speed of the function
        'for very large files.
        CHUNK.SIZE = min(ftcLen, 4096)
 
        while not(eof(#fileToCopy))
            'Smaller of max size or bytes still unread.
            chunk   = min(ftcLen, CHUNK.SIZE)
 
            'Read certain amount of file into a buffer.
            buffer$ = input$(#fileToCopy, chunk)
 
            'Decrement remaining byte count by how much
            'was read.
            ftcLen  = ftcLen - chunk
            #copyToFile buffer$;
        wend
 
        close #fileToCopy
        close #copyToFile
 
        CopyFile = 1
    end if
end function