开发者

strange file reading problem in c++: fread()

开发者 https://www.devze.com 2023-01-06 01:20 出处:网络
I have a very strange problem when reading a binary file. void metaDataProcess(FILE *f){ unsigned __int32 obLength;

I have a very strange problem when reading a binary file.

void metaDataProcess(FILE *f){

    unsigned __int32 obLength;
    unsigned __int32 numProp;
    char* objPath;
    unsigned __int32 rawDataIndex;
    int level;
    fread(&obLength,sizeof(obLength),1,f);
    objPath=new char[obLength];
    cout<<"i am at"<<ftell(f)<<endl;
    fread(&objPath,sizeof( char),obLength,f);
    objPath[obLength]='\0';
    cout<<"i am at"<<ftell(f)<<" the object path is "<<objPath<<endl;
level=getOrCreateNode(objPath);

fread(&rawDataIndex,sizeof(rawDataIndex),1,f);

the "objPath" didnt get what is expected in that location. In 010 editor, for that location it is '/', but i read it as '>'. it is quite strange, since from the print out value of ftell, it is the correct position and the value read before and 开发者_如何学运维after that are got expected value(obLength=1; and next value rawDataIndex==4294967295).

how come i got '>' when i expceted '/'. i tried fread(&objPath,sizeof(unsigned char),obLength,f); fread(&objPath,1, obLength,f); they are all '>'; can anyone help me with it? thanks


objPath=new char[obLength + 1];
cout<<"i am at"<<ftell(f)<<endl;
fread(objPath,sizeof( char),obLength,f);
objPath[obLength]='\0';


I can't see anything wrong with the code above, except that you are acessing an ilegal memory position, since you allocate:

objPath=new char[obLength];

and then do:

objPath[obLength]='\0';

You should have allocated new char[obLength+1] to reserve enough space for the '\0'.

The other thing is that you are printing the result of ftell after reading the file. Is that what you want really?


Is your 010 editor showing position in hex rather than decimal? You're programmatically printing it in decimal so that could account for the difference you're seeing.

EDIT: What does your file look like? Is the < one character off from the / you expect? Have you tried reading the characters one at a time and finding out which offset the / actually exists at?

0

精彩评论

暂无评论...
验证码 换一张
取 消