给定一个位于“C:MyFile.csv”的文件和一个字符数组缓冲区size 10,000,如何有效地将文件中的所有字节读取到缓冲区中?
考虑以下方法,在这种情况下通常优于使用 getline():
<code class="cpp">// Open the file in binary mode to preserve byte-by-byte fidelity std::ifstream infile("C:\MyFile.csv", std::ios_base::binary); // Determine the file's size infile.seekg(0, std::ios::end); size_t file_size = infile.tellg(); infile.seekg(0, std::ios::beg); // Ensure that the buffer is of sufficient size if (file_size > sizeof(buffer)) { // Handle the case where the file exceeds the buffer's capacity } // Read the entire file's contents into the buffer infile.read(buffer, file_size); // Obtain the actual number of bytes read from the file std::streamsize bytes_read = infile.gcount();</code>
附加说明:
以上是如何在 C 语言中高效地将文件中的所有字节读取到字符数组中?的详细内容。更多信息请关注PHP中文网其他相关文章!