memchr一个bin文件

时间:2011-12-23 10:54:24

标签: c++ c

我正在尝试在二进制文件中查找0x0D0A。但是strchr在找到0x00时停止并且我没有得到正确的位置。

请告诉我它为什么不起作用

#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);
}

4 个答案:

答案 0 :(得分:7)

使用memchr查找'\ r',然后测试'\ n'是否是下一个字符。

答案 1 :(得分: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的答案。

答案 2 :(得分:3)

嗯,你已经解释过一个原因(可能是嵌入式NUL)。另一个原因是你最后没有添加NUL字符。第三个原因是您0x0D0A strchr不是一个角色。

您可以使用memchr来完成作业的部分(搜索0x0D)。如果沿着这条路走下去,你必须自己检查0x0A

答案 3 :(得分:0)

memchar返回一个地址,因为你找到了第一次使用0x0D的地址并将其存储在p中,那么你在同一个地址找不到0x0A甚至另一个0x0D。尝试derefencing p和memchar的返回值,看看他们指的是假设你正在寻找不是地址的字符。