CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Threaded View

  1. #1
    Join Date
    Sep 1999
    Location
    France
    Posts
    393

    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!
    Last edited by F.Mayis; December 8th, 2006 at 03:58 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured