2012-03-25 135 views
1

我有一個二進制文件,我想正則表達式搜索/替換其中的十六進制字節。我知道用Perl實現這個命令行方法,但是,如果有一種方法可以用Objective-C/Cocoa來完成,我一直無法找到它。從在OSX命令行Perl的方法,該方法工作得很好,雖然我想在Cocoa應用程序將這類 - 感謝Objective-C正則表達式替換十六進制字節?

二進制文件:TEST

45 76 65 6E 20 69 66 20 79 6F 75 20 66 61 6C 6C 20 6F 6E 20 79 6F 75 72 20 66 61 63 65 2C 20 79 6F 75 27 72 65 20 73 74 69 6C 6C 20 6D 6F 76 69 6E 67 20 66 6F 72 77 61 72 64 2E 20 

字節來替換:66 61 63 替換用:61 72 73

的Perl例如:

# grep -Z -r -l face TEST | xargs -0 perl -pi -e "s/\x66\x61\x63/\x61\x72\x73/g" 

回答

3

沿着這個東西線應該工作:

// Change TEST to the absolute path of the file to read the data from 
NSString *fileName = @"TEST"; 
NSMutableData *data = [NSMutableData dataWithContentsOfFile:fileName]; 
if (data == nil || [data length] == 0) { 
    return; 
} 

你原來的問題:

char bytes[]  = {0x66, 0x61, 0x63}; 
char new_bytes[] = {0x61, 0x72, 0x73}; 

NSRange range = [data rangeOfData:[NSData dataWithBytes:bytes length:3] options:0 range:NSMakeRange(0, [data length])]; 
if (range.location == NSNotFound) { 
    return; 
} 

[data replaceBytesInRange:range withBytes:new_bytes]; 
[data writeToFile:fileName atomically:YES]; 

編輯的通配符(我只是用-1通配符,它​​可以在任何點):

char bytes[]  = {0x66, -0x1, 0x63}; 
char new_bytes[] = {0x61, 0x72, 0x73}; 

NSUInteger dataLength = [data length]; 
if (dataLength < 3) { 
    return; 
} 

char *data_bytes = (char *)[data bytes]; 

int dataLengthMinus3 = dataLength - 3; 

for (NSUInteger i = 0; i < dataLengthMinus3; i++) { 
    if (bytes[0] == -0x1 || data_bytes[i] == bytes[0]) { 
     if (bytes[1] == -0x1 || data_bytes[i+1] == bytes[1]) { 
      if (bytes[2] == -0x1 || data_bytes[i+2] == bytes[2]) { 
       for (int z = 0; z < 3; z++) { 
        if (new_bytes[z] != -0x1){ 
         [data replaceBytesInRange:NSMakeRange(i+z, 1) withBytes:new_bytes[z]]; 
        } 
       } 
       i += 2; 
       continue; // Make this break if you only want to replace the first occurrence. 
      } 
     } 
    } 
} 
+0

@Inafziger,感謝例。我編譯了你的代碼(沒有錯誤),運行它(沒有錯誤),儘管該文件保持不變。一切似乎都應該起作用,所以我有點困惑。如果你有任何想法,讓我知道。 – 2012-03-25 06:20:50

+0

您是否在調試器中逐步查看它是否返回早? '字節\t炭[3] \t [0] \t炭\t 'B' [1] \t炭\t '=' [2] \t炭\t': – lnafziger 2012-03-25 10:27:08

+0

運行看來它尋找這個調試器後? ''和newbytes是:'new_bytes \t炭[3] \t [0] \t \t炭 '=' [1] \t \t炭 'H' [2] \t \t炭' I'' - 因此它看起來像編碼問題? – 2012-03-25 10:48:00