I am working on Windows OS with Visual Studio 2017, and I obtained the following function to determine the size of a file from one of SO's answers:
__int64 FileSize(const char *filename)
{
HANDLE hFile = CreateFile(filename, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return -1; // error condition, could call GetLastError to find out more
}
LARGE_INTEGER size;
if (!GetFileSizeEx(hFile, &size)) {
CloseHandle(hFile);
return -1; // error condition, could call GetLastError to find out more
}
CloseHandle(hFile);
return size.QuadPart;
}
So, am using it to determine a file size, in order to allocate memory dynamically accordingly with malloc(). Since the function malloc() accept a size_t type, I assigned the return value of FileSize() function to a size_t variable, but I got the following warning:
main.cpp(67): warning C4244: 'initializing': conversion from '__int64' to '::size_t', possible loss of data
In this case, How would I safely store the size of the file within a size_t variable? I know I could cast the return value to size_t and dismiss the warning, but would it be safe/correct?