std::fread
來自 cppreference.com
定義於標頭檔案 <cstdio> |
||
std::size_t fread( void* buffer, std::size_t size, std::size_t count, std::FILE* stream ); |
||
從給定的輸入流 stream 讀取至多 count 個物件到陣列 buffer 中,就像對每個物件呼叫 std::fgetc size 次,並將結果按順序儲存到 buffer 的連續位置中,buffer 被重新解釋為 unsigned char 陣列。流的檔案位置指示器將按讀取的字元數前進。
如果物件不是 TriviallyCopyable 的,則行為未定義。
如果發生錯誤,流的檔案位置指示器的最終值是不確定的。如果讀取了部分元素,其值是不確定的。
目錄 |
[編輯] 引數
buffer | - | 指向要讀取的陣列中第一個物件的指標 |
size | - | 每個物件的大小(以位元組為單位) |
count | - | 要讀取的物件數量 |
stream | - | 要從中讀取的輸入檔案流 |
[編輯] 返回值
成功讀取的物件數量,如果發生錯誤或到達檔案末尾,則可能小於 count。
如果 size 或 count 為零,fread
返回零且不執行其他操作。
fread
不區分檔案末尾和錯誤,呼叫者必須使用 std::feof 和 std::ferror 來確定發生了哪種情況。
[編輯] 示例
執行此程式碼
#include <cstddef> #include <cstdio> #include <fstream> #include <iomanip> #include <iostream> #include <vector> int main() { // Prepare file std::ofstream("test.txt") << 1 << ' ' << 2 << '\n'; std::FILE* f = std::fopen("test.txt", "r"); std::vector<char> buf(4); // char is trivially copyable const std::size_t n = std::fread(&buf[0], sizeof buf[0], buf.size(), f); std::cout << "Read " << n << " object" << (n > 1 ? "s" : "") << ": " << std::hex << std::uppercase << std::setfill('0'); for (char n : buf) std::cout << "0x" << std::setw(2) << static_cast<short>(n) << ' '; std::cout << '\n'; std::vector<std::string> buf2; // string is not trivially copyable // This would result in undefined behavior: // std::fread(&buf2[0], sizeof buf2[0], buf2.size(), f); }
可能的輸出
Read 4 objects: 0x31 0x20 0x32 0x0A
[編輯] 參閱
從 stdin、檔案流或緩衝區讀取格式化輸入 (函式) | |
從檔案流獲取字元字串 (函式) | |
寫入檔案 (函式) | |
C 文件 用於 fread
|