Search code examples
c++sizebufferreadlinefread

c++ How do I find length of buffer in non-windows platforms using fread()


I have a function using ReadFile() where I append a '\0' at the end of the buffer :

HANDLE InFile;
FILE* InputFile;
DWRD len = ftell(InputFile);   
buffer = new BYTE[len + 1];  

if (ReadFile(InFile, buffer , len, &len2, NULL))
{
   ...
   buffer [len2] = 0;      
}

Now I want to adapt this function for use with non-windows platforms. I already changed ReadFile() and use fread() now. But then I do not have len2 available which I would like to use for appending the '\0':

FILE* InputFile;
DWRD len = ftell(InputFile);   
buffer = new BYTE[len + 1];  

if (fread(buffer ,1,len,InputFile)) 
{         
  // how can I find the length of the buffer (len2) now ? 
  buffer [len2] = 0;  // Does not work !       
  ...
}

How can I get the position of the end of my buffer ?


Solution

  • fread() returns the numbers of items actually read, eg:

    FILE* InputFile;
    ...
    DWORD len = ftell(InputFile);   
    buffer = new BYTE[len + 1];  
    
    size_t len2;
    if ((len2 = fread(buffer, 1, len, InputFile)) > 0)
    {         
      buffer [len2] = 0;
      ...
    }
    else 
    {
        // use feof() and ferror() to check for errors...
    }