java读取4个字节_一次读取4个字节 (Reading in 4 bytes at a time)

本文介绍如何在Java中通过重载`operator>>`以每次读取4个字节的方式处理输入流,利用部分特化`basic_istream`类模板实现,并给出不同方法的示例,包括一次性读取整数和读取整个文件的数据。
摘要由CSDN通过智能技术生成

最佳答案

英文原文

To read by 4 bytes from ifstream you could overload operator>> as follows (it is actually a partial specialization of the basic_istream class template so istream_iterator could use operator>> from it. Class basic_ifstream is used here to inherit all input file stream functionality from it):

#include

typedef unsigned int uint32_t;

struct uint32_helper_t {};

namespace std {

template

class basic_istream : public basic_ifstream {

public:

explicit basic_istream(const char* filename,

ios_base::openmode mode ) : basic_ifstream( filename, mode ) {}

basic_istream& operator>>(uint32_t& data) {

read(&data, 1);

return *this;

}

};

} // namespace std {}

Then you could use it in the following way:

std::basic_istream my_file( FILENAME, std::ios::in|std::ios::binary );

// read one int at a time

uint32_t value;

my_file >> value;

// read all data in file

std::vector data;

data.assign( std::istream_iterator(my_file),

std::istream_iterator() );

中文翻译

要从ifstream读取4个字节,您可以按如下方式重载operator>>(它实际上是basic_istream的部分特化类模板,所以istream_iterator可以使用operator>>。这里使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值