Today, I will show you how to unarchive the archive file that I programmed in the previous post.
First, I want to load my archive file into a byte array.
def unarchive(file_name): with open(file_name,"rb") as f: f_buf = f.read() for bt in f_buf: arc_buf.append(bt) arc_size = len(arc_buf)
To make the unarchiving algorithm, I need to make some arrays to store the data I get by unarchiving.
file_names =  fn_buf = "" file_contents =  fc_buf = bytearray()
Now I can start the algorithm:
#0 = look for new file #1 = look for file name #2 = read file name and look for file content #3 = read file content and look for new file mode = 0 i = 0
So, I want to read signatures from the buffer and write some data to arrays.
while i < arc_size: if mode == 0: #Clean nfb_cmp nfb_cmp =  #Read 5 bytes from arc_buf and add to nfb_cmp for bt in arc_buf[i:i+5]: nfb_cmp.append(bt) if nfb_cmp == new_file_bytes i +=4 #move pointer after signature #Why not +5?Beacuse we have +1 in the bottom of the loop #and becuse we have elif instead of if, next mode will be executed #in next iteration mode = 1 elif mode == 1: fnb_cmp =  for bt in arc_buf[i:i+5]: fnb_cmp.append(bt) if fnb_cmp == file_name_bytes: i +=4 mode = 2 elif mode == 2: fcb_cmp =  for bt in arc_buf[i:i+5]: fcb_cmp.append(bt) if fcb_cmp == file_content_bytes: file_names.append(fn_buf) fn_buf = "" i +=4 mode = 3 else:fn_buf += chr(arc_buf[i]) elif mode == 3: nfb_cmp =  for bt in arc_buf[i:i+5]: nfb_cmp.append(bt) if nfb_cmp == new_file_bytes: file_contents.append(fc_buf) fc_buf = bytearray() i +=4 mode = 1 else:fc_buf.append(arc_buf[i]) i +=1 file_contents.append(fc_buf) #Because we don't use end file signature, we have to manually append file #content buffer after loop
Finally, I can save data to files.
i = 0 while i < len(file_names): with open(file_names[i],"wb") as f: f.write(file_contents[i]) i += 1 print("DONE")