我試圖尋找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);
}
你知道原因,你問爲什麼它不工作? – 2011-12-23 10:55:37
我想他是在尋求補救措施 – akappa 2011-12-23 10:58:42
您可能只需在您的文件上使用'mmap',然後使用@Mario的解決方案。 – hochl 2011-12-23 11:47:50