2014-01-17 48 views
0
#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 

int main() 
{ 

FILE *file,*fileout; 
unsigned char data[1]; 

    uint8_t what[] = {0x00, 0xEB, 0x00, 0x00, 0x50, 0xE3, 0x02}; 
uint8_t repl[] = {0x00, 0xEB, 0x01, 0x00, 0x37, 0xB3, 0x02}; 

    uint8_t *buf_find(uint8_t *p, uint8_t *end, uint8_t *needle, int len) 
    { 
     end = end - len + 1; 

    while (p < end) { 
     if (memcmp(p, needle, len) == 0) return p; 
     p++; 
    } 
    return NULL; 
} 



file=fopen("test.bin","rb"); 
fileout=fopen("test.bin.bak","wb"); 

while (!feof(file)) { 
if (fread(data, 1, 1, file) > 0) {  

    char *p = data; 
     char *end = data + 1;  
     for (;;) { 
      uint8_t *q = buf_find(p, end, what, sizeof(what)); 
      if (q == NULL) break; 
       memcpy(q, repl, sizeof(repl)); 
       p = q + sizeof(data[0]); 
     } 

    printf("%02X ",data[0]); 
    fwrite(&data,1,1,fileout); 
} 
} 

fclose(file); 
fclose(fileout); 
return 0; 
} 

如何更改二進制文件中的二進制文件十六進制字符? 閱讀十六進制=「00 EB 00 00 50 E3 02」替換十六進制=「00 EB 01 00 37 E3 02」查找和替換十六進制

我的問題回答了,但它很慢。 Hexadecimal find and replace

+0

穆罕默德,你讀通過byte_文件_byte並嘗試rading每個字節後替換字符串?當然它會很慢。閱讀整個文件或大塊(如您在原始問題中所做的那樣),然後在該塊上運行'buf_find'。或者在下面的答案中使用流方法。 –

回答

1

試試這個

#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 


size_t replace(FILE *fi, FILE *fo, uint8_t *what, uint8_t *repl, size_t size){ 
    size_t i, index = 0, count = 0; 
    int ch; 
    while(EOF!=(ch=fgetc(fi))){ 
     if(ch == what[index]){ 
      if(++index == size){ 
       for(i = 0; i < size ; ++i){ 
        fputc(repl[i], fo); 
       } 
       index = 0; 
       ++count; 
      } 
     } else { 
      for(i = 0; i < index ; ++i){ 
       fputc(what[i], fo); 
      } 
      index =0; 
      fputc(ch, fo); 
     } 
    } 
    for(i = 0; i < index ; ++i){ 
     fputc(what[i], fo); 
    } 

    return count; 
} 

int main(void){ 
    FILE *file,*fileout; 
    uint8_t what[] = {0x00, 0xEB, 0x00, 0x00, 0x50, 0xE3, 0x02}; 
    uint8_t repl[] = {0x00, 0xEB, 0x01, 0x00, 0x37, 0xB3, 0x02}; 
    size_t count; 

    file=fopen("test.bin","rb"); 
    fileout=fopen("test.bin.bak","wb"); 
    count = replace(file, fileout, what, repl, sizeof(what)); 
    printf("number of replace count is %zu\n", count); 
    fclose(fileout); 
    fclose(file); 
    return 0; 
} 
+0

yess非常好大謝謝它沒關係,以及兩個什麼和兩個repl發送函數,但what1和repl1確定what2和repl2失敗:( –

+0

@Mehmet_我不知道你在說什麼 – BLUEPIXY

+0

好吧,我的問題解決了非常感謝@ M Oehm an @BLUEPIXY –