Home > Article > Backend Development > How to Read File Bytes into a Char Array in C Without getline()?
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:
<code class="cpp">std::ifstream infile("C:\MyFile.csv");</code>
Get File Length:
<code class="cpp">infile.seekg(0, std::ios::end); size_t length = infile.tellg(); infile.seekg(0, std::ios::beg);</code>
Ensure Buffer Size:
<code class="cpp">if (length > sizeof (buffer)) { length = sizeof (buffer); }</code>
Read the File:
<code class="cpp">infile.read(buffer, length);</code>
Additional Notes:
Updated Approach (2019):
To account for potential errors during reading, consider the following approach:
<code class="cpp">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</code>
The above is the detailed content of How to Read File Bytes into a Char Array in C Without getline()?. For more information, please follow other related articles on the PHP Chinese website!