Main Menu

Copy Bytes Between Files

Started by kevin, April 01, 2010, 08:34:53 AM

Previous topic - Next topic

kevin

 Copy Bytes Between Files

 This example includes a function to copy a section of one file into another.   The example is setup to merge to big files into a 3rd.  I used this to correct errors in some big movie files.   Thankfully there was two copies of the file,  in copy one, the first half was ok, but the second halve was broken. In the other copy of the same file (on a different HD) the reverse was true, the start was broken but the end was ok.  So I used this to join the two good bits into a working file (i just guessed the split point)..     While it's unlikely you'll run into this same situation,  the copy bytes function could come in handy for things such as joining files together.  


PlayBASIC Code: [Select]
   SrcFile1$="File1.txt"
SrcFile2$="File2.txt"

DestFile$="outputfile.txt"

if fileexist(SrcFile1$) and Fileexist(SrcFile2$)

size=FileSize(SrcFile1$)
print size
print FileSize(SrcFile2$)

IF FileExist(destFile$)=false
MakeFile DestFile$,size
EndIF

CutPoint=Size*0.6
print CutPoint
SrcStartPos=0
SrcEndPoS=CutPoint
DestPos=SrcStartPos
print "File#1"
CopyBytesBetweenFiles(SrcFile1$,SrcStartPos,SrcEndPos,DestFile$,DestPos)


SrcStartPos=CutPoint
SrcEndPoS=Size
DestPos=SrcStartPos
print "File#2"
CopyBytesBetweenFiles(SrcFile2$,SrcStartPos,SrcEndPos,DestFile$,DestPos)

endif

print "DONE"

Sync
waitkey


Function CopyBytesBetweenFiles(SrcFile$,SrcStartPos,SrcEndPos,DestFile$,DestPos)

CacheSize=1024*1024

ThisBank=NewBank(CacheSize+256)

Size=SrcEndPos-SrcStartPos

Chunks=Size/CacheSize

SrcFileSize=FileSize(SrcFile$)
SrcFile=ReadNewFile(SrcFile$)
DestFile=OpenNewFile(DestFile$)
FilePos SrcFile,StartPOs
FilePos DestFile,StartPOs

SrcPos=SrcStartPos

X=getcursorX()
Y=getcursorY()

For ThisChunk=1 to Chunks
Filepos SrcFile,SrcPos
Filepos DestFile,DestPos+(SrcPos-SrcStartpos)
ReadMemory SrcFile,GetBankPtr(ThisBank),CacheSize
WriteMemory DestFile,GetBankPtr(ThisBank),GetBankPtr(ThisBank)+CacheSize
boxC x,y,x+800,y+32,true,0
text x,y,ThisChunk
Sync
SrcPos+=CacheSize
next

bytesCopied=SrcPos-SrcStartPos
if BytesCopied<Size

Filepos SrcFile,SrcPos
Filepos DestFile,DestPos+(SrcPos-SrcStartpos)
ChunkSize=Size-BytesCopied
ReadMemory SrcFile,GetBankPtr(ThisBank),ChunkSize
WriteMemory DestFile,GetBankPtr(ThisBank),GetBankPtr(ThisBank)+ChunkSize
endif

CloseFile SrcFile
CloseFile DestFile
DeleteBank ThisBank
print ""

Endfunction