不久前,我在一个垂死的硬盘上做了两次拯救尝试;我首先运行了(GNU) ddrescue,然后用手动搜索直接运行了dd。我想从这两张照片中得到最好的效果。因为文件中的任何空位都是0's,按位计算,应该足以合并这两个文件。
(我正在使用ArchLinux,但如果它不在repos中,我很乐意从源代码中安装)
发布于 2016-11-04 19:41:07
我不知道有什么实用程序可以做到这一点,但是编写一个程序来实现这一点应该是相当容易的。下面是python中的一个骨架示例:
#!/usr/bin/env python
f=open("/path/to/image1","rb")
g=open("/path/to/image2","rb")
h=open("/path/to/imageMerge","wb") #Output file
while True:
data1=f.read(1) #Read a byte
data2=g.read(1) #Read a byte
if (data1 and data2): #Check that neither file has ended
h.write(chr(ord(data1) | ord(data2))) #Or the bytes
elif (data1): #If image1 is longer, clean up
h.write(data1)
data1=f.read()
h.write(data1)
break
elif (data2): #If image2 is longer, clean up
h.write(data2)
data2=g.read()
h.write(data2)
break
else: #No cleanup needed if images are same length
break
f.close()
g.close()
h.close()或者一个应该运行得更快的C程序(但很可能有一个未被注意到的bug):
#include <stdio.h>
#include <string.h>
#define BS 1024
int main() {
FILE *f1,*f2,*fout;
size_t bs1,bs2;
f1=fopen("image1","r");
f2=fopen("image2","r");
fout=fopen("imageMerge","w");
if(!(f1 && f2 && fout))
return 1;
char buffer1[BS];
char buffer2[BS];
char bufferout[BS];
while(1) {
bs1=fread(buffer1,1,BS,f1); //Read files to buffers, BS bytes at a time
bs2=fread(buffer2,1,BS,f2);
size_t x;
for(x=0;bs1 && bs2;--bs1,--bs2,++x) //If we have data in both,
bufferout[x]=buffer1[x] | buffer2[x]; //write OR of the two to output buffer
memcpy(bufferout+x,buffer1+x,bs1); //If bs1 is longer, copy the rest to the output buffer
memcpy(bufferout+x,buffer2+x,bs2); //If bs2 is longer, copy the rest to the output buffer
x+=bs1+bs2;
fwrite(bufferout,1,x,fout);
if(x!=BS)
break;
}
}发布于 2019-11-01 21:01:23
with open('file1', 'rb') as in1, open('file2', 'rb') as in2, open('outfile', 'wb') as out:
while True:
bytes1 = in1.read(1024)
bytes2 = in2.read(1024)
if not bytes1 or not bytes2:
break
out.write(bytes(b1 | b2 for (b1, b2) in zip(bytes1, bytes2)))由于一次读取1024字节,这大约比Chris的Python解决方案快10×10。它还使用with open模式,因为这在关闭文件时更可靠(例如,在出现错误的情况下)。
这似乎适用于Python3.6.3(成功合并了2个部分torrent文件),但还没有经过彻底的测试。
也许可以删除if ...: break模式,而使用while in1 or in2:
发布于 2019-11-01 21:48:14
这不是按位或,但它适用于(整块)零:
dd conv=sparse,notrunc if=foo of=baz
dd conv=sparse,notrunc if=bar of=baz由于sparse,它跳过编写源文件中任何为零的内容。
所以baz看起来像bar,加上在bar中是零的,而在foo中则不是零。
换句话说,如果在foo和bar中有不相同的非零数据,bar就会赢。
https://unix.stackexchange.com/questions/321119
复制相似问题