2011-12-23 45 views
1

我試圖尋找0x0D0A在一個二進制文件,但是當它發現0x00,而我沒有得到正確的位置,和strchr停止。了memchr bin文件

請告訴我,爲什麼它不工作

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <windows.h> 

main(){ 
    FILE *f; 
    long size; 
    char *buffer; 

    f = fopen(filename, "rb"); 
    if(f==NULL){fputs("File error",stderr); exit(1);} 

    // obtain file size 
    fseek(f, 0, SEEK_END); 
    size = ftell(f); 
    rewind(f); 

    // allocate memory to contain the whole file 
    buffer = (char*) malloc(sizeof(char)*size); 
    if(buffer == NULL){fputs("Memory error",stderr); exit(2);} 

    // copy the file into the buffer 
    if((size_t)fread(buffer,1,size,f) != size){fputs("Reading error",stderr); exit(3);} 
    fclose(f); 

    // get positions 
    char *p; 
    p = strchr(buffer, 0x0D0A); 
    while(p != NULL){ 
     printf("found at %d\n", p-buffer-1); 
     p = strchr(p+2, 0x0D0A); 
    } 

    free(buffer); 
    return 0; 
} 

更新

if(((char*) memchr(p+1, 0x0A, size))-1 == p)不起作用現在

int *pos,i=0; 
char *p; 
p = (char*) memchr(buffer, 0x0D, size); 
while(p != NULL){ 
    if(((char*) memchr(p+1, 0x0A, size))-1 == p){ 
     pos[i++] = p-buffer-1; 
     printf("found at %d\n", pos[i-1]);// check 
    } 
    p = (char*) memchr(p+2, 0x0D, size); 
} 
+0

你知道原因,你問爲什麼它不工作? – 2011-12-23 10:55:37

+0

我想他是在尋求補救措施 – akappa 2011-12-23 10:58:42

+0

您可能只需在您的文件上使用'mmap',然後使用@Mario的解決方案。 – hochl 2011-12-23 11:47:50

回答

4

對於二進制數據,您不能使用str...()函數,因爲它們僅用於字符串(以memcpy()strcpy()爲例)。

你只需要做一個簡單的循環:

unsigned int pos = 0; 

while(pos + 1 < size) // compare with +1 as we won't check the last char in the buffer 
{ 
    if(buffer[pos] = 0x0d && buffer[pos+1] == 0x0a) 
     printf("found at %d\n", pos); 
    ++pos; 
} 

也請記住,取決於文件大小,你可能想不讀整個文件到內存中一次。至於其他錯誤,請參閱aix的答案。

3

嗯,你已經解釋的一個原因(可能嵌入式NUL)。另一個原因是你最後沒有添加NUL字符。第三個原因是你給strchr0x0D0A不是一個字符。

您可以使用memchr部分的工作(搜索0x0D)。如果你沿着這條路線走,你必須自己檢查0x0A

+0

了memchr解決的第一個部分,但與4 0x0D0A返回8位bin文件 – 2011-12-23 11:04:44

+0

我認爲它只是尋找的0x0A不是0x0D0A – 2011-12-23 11:09:48

+0

它會搜索你問的性格它不會更多,也不會少。它不能一次搜索兩個字符,正如我的答案的最後一句所解釋的那樣。 – NPE 2011-12-23 11:11:26

7

使用了memchr找到「\ r」,然後測試,如果「\ n」是下一個字符。

+1

+1總是善於使用簡單的設計。 – hochl 2011-12-23 11:46:16

0

memchar返回一個地址,並且由於您發現第一個地址爲0x0D的地址並將其存儲在p中,因此您無法在同一地址找到0x0A或甚至另一個0x0D。嘗試去掉p和memchar的返回值,看看他們指着什麼,假設你正在尋找字符而不是他們的地址。