Home > Blockchain >  Using heap memory for reading files
Using heap memory for reading files

Time:12-06

To read data from a file, I create heap memory then pass the variable pointer to a function so fread() will put the file data into the pointer. But when the function returns, there is no data in the new created memory.

int main(...) {
  MyFile File;
  File.Open(...);
  int filesize = File.Tell();
  char* buffer = new buffer[filesize]; // Create some memory for the data 
  File.Read((char**)&buffer);

  // Now do something with the buffer. BUT there is trash in it.

  File.Close();
  delete [] buffer;
}

size_t File::Read(void* buf) {
  ...

  ::fseek(fStream, 0, SEEK_END);
  int fileSize = ::ftell(fStream);  // Get file size.
  ::fseek(fStream, 0, SEEK_SET);

  ::fread(buf, 1, fileSize, fStream);

  return (fileSize);
}

Yes, I can put char * myBuffer = new char[fileSize]; inside of File::Read(...) before ::fread(myBuffer, 1, fileSize, fStream);, but I should not have to do this because I already have heap memory (buffer) in main().

CodePudding user response:

You're reading your file contents into the pointer buffer, not the array it points to.

You're overcomplicating things anyway. You don't need a pointer to a pointer, or a void*. You can simply pass a char* to Read. You should really also pass the size of the buffer pointed to into Read as well. Otherwise you risk overflowing your buffer.

int main() {
    MyFile File;
    File.Open(/*.....*/);
    int filesize = File.Tell()
    char* buffer = new buffer[filesize]; // Create some memory for the data 
    File.Read(buffer, filesize);

    // Now do something with the buffer. BUT there is trash in it.

    File.Close();
    delete [] buffer;
}

size_t File::Read(char* buf, size_t count) {
    // ......

    // No need to find the size of the file a second time

    // Return the actual number of bytes read
    return ::fread(buf, 1, count, fStream);
}

CodePudding user response:

I change my function to,

size_t nvFile::Read( char * pszBuffer, const size_t uiCount ) ...

Thank you Miles Budnek! I did not think enought of my problem. I am opening a binary file and it is a byte (char), so it not have to be void *. (I put on my 'cone-of-shame' for not thinking.)

Thank you for help and makeing me think more. :)

  • Related