C++:通过ifstream读取二进制文件内容

386 篇文章 ¥99.90 ¥299.90
本文介绍了如何在C++中利用ifstream以二进制模式读取文件。通过设置std::ios::binary标志,可以确保文件内容按二进制格式正确读取。示例程序展示了如何使用tellg函数获取文件大小,并输出了读取的二进制数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过构造ifstream对象时指定std::ios::binary可以要求以二进制形式读取文件。

然后可以通过tellg函数获取文件的大小。

#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <format>
using namespace std;

vector<unsigned char> readBinaryDataFromFile(const string& filePath)
{
    vector<unsigned char> ret;
    ifstream is{filePath, ios::binary | ios::ate};
    if(is)
    {
        auto fileSize = is.tellg();
        vector<unsigned char> binData(fileSize);;
        is.seekg(0);
        if(is.read((char*)&(binData[0]), fileSize))
        {
            ret = move(binData);
        }
    }
    return ret;
}

int main()
{
    vector<unsigned char>&& data = readBinaryDataFromFile("./ff");
    for(a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风静如云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值