std::fread
来自cppreference.com
| 在标头 <cstdio> 定义
|
||
| |
||
从给定输入流 stream 读取至多 count 个对象到数组 buffer 中,如同以对每个对象调用 size 次 std::fgetc,并按顺序存储结果到判读为 unsigned char 数组的 buffer 中的相继位置。流的文件位置指示器前进读取的字符数。
若对象不可平凡复制 (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()
{
// 准备文件
std::ofstream("test.txt") << 1 << ' ' << 2 << '\n';
std::FILE* f = std::fopen("test.txt", "r");
std::vector<char> buf(4); // char 可平凡复制
const std::size_t n = std::fread(&buf[0], sizeof buf[0], buf.size(), f);
std::cout << "读取了 " << n << " 个对象: "
<< 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 不可平凡复制
// 这会导致未定义行为
// std::fread(&buf2[0], sizeof buf2[0], buf2.size(), f);
}
可能的输出:
读取了 4 个对象: 0x31 0x20 0x32 0x0A
参阅
| 从 stdin、文件流或缓冲区读取有格式输入 (函数) | |
| 从文件流获取字符串 (函数) | |
| 写入文件 (函数) | |
fread 的 C 文档
| |