File relative
How to read the file
-
std::ifstreaminput stream, for reading files -
file()file function, ( filepath ,bit flags(open mode)) -
std::ios::ateat the end, this mean once the file open we seek the end immediately -
std::ios::binaryopen the file in binary mode, raw stream of bytes, avoid any unwanted text transformations -
std::ios::ate | std::ios::binarywe want both gpointer o to end the file (so can use tellg()) , and read as binary
why {} instead of ():
-
uniform initialization. so we tell this is object definition, not function declaration.
-
strict type checking, prevent implicit type conversion
Open file error check
if (!file.is_open()){ throw std::runtime_error("fail to open file: " + filepath) //filepath is incorrect or no permission to open the file }File size
the last of file
file.tellg() return std::streamposdata, means the pointer’s location in the file
size_t filesize = static_cast<size_t>(file.tellg());other example:
double value = 3.14;int intValue = static_cast<int>(value); // transfer to >integerstd::cout << intValue; // output: 3the first of the file
file.seekg(0); //move the pointer to the beginningCreate buffer
file.read(buffer.data(), fileSize);
file.close();
return buffer;