Home > Enterprise >  How can i use string instead of char* buffer to read the file data into string?
How can i use string instead of char* buffer to read the file data into string?

Time:02-14

I am using standard file-handler API to read the file , currently I have used char* buffer to read the data but I want to use string so I can avoid calloc use. I tried to pass string address to ReadFile function but its not working... could you please help me???

Thanks in advance !!!

   
l_FileSize = GetFileSize(l_FileHandle, NULL);

char * l_FileBuffer = NULL;

l_FileBuffer = (char *)calloc(l_FileSize, sizeof(char));
     
ReadFile(l_FileHandle,(void *)(l_FileBuffer), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);```

CodePudding user response:

The proper use is std::vector.

l_FileSize = GetFileSize(l_FileHandle, NULL);
std::vector<char>  l_FileBuffer(l_FileSize);
ReadFile(l_FileHandle,l_FileBuffer.data(), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);

Since vector by the standard ensures that the items are stored continuously.

Note that even in this way you are still implicitly allocating memory, it's just that the vector will release it automatically on destruction. If the file is known to be very small then you can afford to load it on a stack-allocated buffer instead.

CodePudding user response:

let's try with std::string

std::string  l_FileBuffer;
read(fd, (char*)(l_FileBuffer.data()), l_FileSize );

after that you can process l_FileBuffer with APIs from std::string easier

  • Related