Reading string from binary file
Hi,
I have existing binary files where strings are stored with '\0' at the end.
Code:
CString s;
res = WriteFile(hFile,(LPCSTR)s, s.GetLength() + 1, &dw,NULL);
NB: it's like that and cannot be changed.
so each time I read a file I need to go and search the \0 to reconstruct the string.
There was existing code to read that but it was not efficient. I changed it but please can you tell me if someone have most efficient way or is there improvement that can be bring to the following code (of course they are ;-) )
Code:
do{
if ( !ReadFile(hFile,&c, 1, &dw,NULL) ) return TRUE;
//End of file no \0 found error
if ( dw != 1 )
return TRUE;
count++;
}while (c != '\0');
//back to the beginning of the string
if ( SetFilePointer(hFile,
-count,
NULL,
FILE_CURRENT) == 0xFFFFFFFF ) return TRUE;
//read the correct buffer size
if ( ReadFile(hFile,(LPSTR)s.GetBuffer(count), count, &dw,NULL) ){
//End of file not all read (???)
if ( dw != count )
return TRUE;
}
//release buffer
s.ReleaseBuffer();
NB : I have to use Win32File, no nested classes like CFile or CStdioFile.
thanks a lot!
Re: Reading string from binary file
since you read byte by byte.... you can store the particular byte read to the char array.. append until you reach a '\0'..... then you got a 1st line of the file..