我试图在二进制文件中查找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;
}
Run Code Online (Sandbox Code Playgroud)
更新
现在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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |