沿着這個東西線應該工作:
// 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.
}
}
}
}
@Inafziger,感謝例。我編譯了你的代碼(沒有錯誤),運行它(沒有錯誤),儘管該文件保持不變。一切似乎都應該起作用,所以我有點困惑。如果你有任何想法,讓我知道。 – 2012-03-25 06:20:50
您是否在調試器中逐步查看它是否返回早? '字節\t炭[3] \t [0] \t炭\t 'B' [1] \t炭\t '=' [2] \t炭\t': – lnafziger 2012-03-25 10:27:08
運行看來它尋找這個調試器後? ''和newbytes是:'new_bytes \t炭[3] \t [0] \t \t炭 '=' [1] \t \t炭 'H' [2] \t \t炭' I'' - 因此它看起來像編碼問題? – 2012-03-25 10:48:00