Search code examples
c++buffercstring

Read CString from buffer with unknown length?


Let's say I have a file. I read all the bytes into an unsigned char buffer. From there I'm trying to read a c string (null terminated) without knowing it's length.

I tried the following:

char* Stream::ReadCString()
{
    char str[0x10000];
    int len = 0;
    char* pos = (char*)(this->buffer[this->position]);
    while(*pos != 0)
        str[len++] = *pos++;
    this->position += len+ 1;
    return str;
}

I thought I could fill up each char in the str array as I went through, checking if the char was null terminated or not. This is not working. Any help?

this->buffer = array of bytes
this->position = position in the array

Are there any other methods to do this? I guess I could run it by the address of the actual buffer: str[len++] = *(char*)(this->buffer[this->position++]) ?

Update: My new function:

char* Stream::ReadCString()
{
    this->AdvPosition(strlen((char*)&(this->buffer[this->position])) + 1);
    return (char*)&(this->buffer[this->position]);
}

and calling it with:

printf( "String: %s\n", s.ReadCString()); //tried casting to char* as well just outputs blank string

Example File: enter image description here


Solution

  • Check this:

    #include <cstring>
    #include <iostream>
    
    class   A
    {
      unsigned char buffer[4096];
      int   position;
    
    public:
      A() : position(0)
      {
        memset(buffer, 0, 4096);
        char        *pos = reinterpret_cast<char*>(&(this->buffer[50]));
        strcpy(pos, "String");
        pos = reinterpret_cast<char*>(&(this->buffer[100]));
        strcpy(pos, "An other string");
      }
    
       const char *ReadString()
      {
        if (this->position != 4096)
          {
            while (std::isalpha(this->buffer[this->position]) == false && this->position != 4096)
                   this->position++;
            if (this->position == 4096)
              return 0;
            void    *tmp = &(this->buffer[this->position]);
            char    *str  = static_cast<char *>(tmp);
            this->position += strlen(str);
            return (str);
          }
        return 0;
      }
    
    };
    

    The reintrepret_cast are only for the init, since you are reading from a file

    int     main()
    {
      A     test;
    
      std::cout << test.ReadString() << std::endl;
      std::cout << test.ReadString() << std::endl;
      std::cout << test.ReadString() << std::endl;
    }
    

    http://ideone.com/LcPdFD

    Edit I have changed the end of ReadString()