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 中,如同以对每个对象调用 size 次 std::fgetc ,并按顺序存储结果到转译为 unsigned char 数组的 buffer 中的相继位置。流的文件位置指示器前进读取的字符数。
若对象不可平凡复制 (TriviallyCopyable) ,则行为未定义。
若出现错误,则流的文件位置指示器的结果值不确定。若读入部分的元素,则元素值不确定。
参数
| buffer | - | 指向要读取的数组中首个对象的指针 |
| size | - | 每个对象的字节大小 |
| count | - | 要读取的对象数 |
| stream | - | 读取来源的输入文件流 |
返回值
成功读取的对象数,若出现错误或文件尾条件,则可能小于 count 。
若 size 或 count 为零,则 fread 返回零且不进行其他动作。
示例
运行此代码
#include <iostream> #include <cstdio> #include <fstream> #include <vector> int main() { // 准备文件 std::ofstream("test.txt") << 1 << ' ' << 2 << '\n'; std::FILE* f = std::fopen("test.txt", "r"); std::vector<char> buf(4); // char 可平凡复制 std::fread(&buf[0], sizeof buf[0], buf.size(), f); for(char n : buf) std::cout << n; std::vector<std::string> buf2; // string 不可平凡复制 // 这会导致未定义行为 // std::fread(&buf2[0], sizeof buf2[0], buf2.size(), f); }
输出:
1 2
参阅
| 从 stdin、文件流或缓冲区读取有格式输入 (函数) | |
| 从文件流获取字符串 (函数) | |
| 写入文件 (函数) |