How to Retrieve File Bytes into a Char Array in C
To read file bytes into a char array without using getline(), consider using ifstream::read(). Follow these steps:
Open the File:
std::ifstream infile("C:\\MyFile.csv");
Get File Length:
infile.seekg(0, std::ios::end);
size_t length = infile.tellg();
infile.seekg(0, std::ios::beg);
Ensure Buffer Size:
if (length > sizeof (buffer)) {
length = sizeof (buffer);
}
Read the File:
infile.read(buffer, length);
Additional Notes:
Updated Approach (2019):
To account for potential errors during reading, consider the following approach:
size_t chars_read;
if (!(infile.read(buffer, sizeof(buffer)))) {
if (!infile.eof()) {
// Handle error during reading
}
}
chars_read = infile.gcount(); // Get actual number of bytes read
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3