이진 파일에서 0x0D0A를 찾으려고하는데 0x00을 찾았을 때 strchr이 멈추고 올바른 위치를 얻지 못합니다.memchr 빈 파일
이
#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);
}
이유를 알면 왜 작동하지 않는지 묻습니다. –
나는 그에게 구제를 요청하고 있다고 생각한다 – akappa
파일에'mmap'을 사용하고 나서 @Mario의 해결책을 사용할 수 있습니다. – hochl