std::basic_istream<CharT,Traits>::read
來自 cppreference.com
< cpp | io | basic istream
basic_istream& read( char_type* s, std::streamsize count ); |
||
從流中提取字元。
行為類似於 UnformattedInputFunction。構造並檢查哨兵物件後,提取字元並將其儲存到字元陣列的連續位置,該字元陣列的第一個元素由 s 指向。字元的提取和儲存會一直持續到滿足以下任一條件:
- count 個字元已被提取和儲存。
- 輸入序列上發生檔案尾條件(在這種情況下,呼叫 setstate(failbit|eofbit))。可以使用 gcount() 查詢成功提取的字元數。
目錄 |
[編輯] 引數
s | - | 指向儲存字元的字元陣列的指標 |
count | - | 要讀取的字元數 |
[編輯] 返回值
*this
[編輯] 異常
如果內部操作丟擲異常,則捕獲該異常並設定 badbit。如果 exceptions() 設定為針對 badbit
丟擲異常,則重新丟擲該異常。
[編輯] 注意
當使用非轉換區域設定(預設區域設定是非轉換的)時,std::basic_ifstream 中此函式的重寫器可以透過重寫 std::streambuf::xsgetn 針對零複製批次 I/O 進行最佳化。
[編輯] 示例
執行此程式碼
#include <cstdint> #include <fstream> #include <iostream> #include <sstream> #include <string> int main() { // read() is often used for binary I/O std::string bin = {'\x12', '\x12', '\x12', '\x12'}; std::istringstream raw(bin); std::uint32_t n; if (raw.read(reinterpret_cast<char*>(&n), sizeof n)) std::cout << std::hex << std::showbase << n << '\n'; // prepare file for next snippet std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3"; // read entire file into string if (std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) { auto size = is.tellg(); std::string str(size, '\0'); // construct string to stream size is.seekg(0); if (is.read(&str[0], size)) std::cout << str << '\n'; } }
輸出
0x12121212 abcd1 abcd2 abcd3
[編輯] 另請參閱
插入字元塊 ( std::basic_ostream<CharT,Traits> 的公共成員函式) | |
提取格式化資料 (公共成員函式) | |
提取已有的字元塊 (公共成員函式) | |
提取字元 (公共成員函式) | |
提取字元直到找到給定字元 (公共成員函式) | |
從檔案讀取 (函式) |