給定一個位於「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中文網其他相關文章!