Overview
入力ストリームからデータを読み込む際の補助関数群です.現在では,read(), および get() 関数を提供しています.各関数の最後の引数には,ストリームのエンディアンを指定する事ができます. 引数に指定できる値は,以下の通りです.
- endian::none ..... 実行環境のエンディアンと同じ
- endian::little ..... リトル・エンディアン
- endian::big ..... ビッグ・エンディアン
get() の格納先の変数,および read() の格納先のコンテナの各要素の型が 1 バイトよりも大きな型 (short, int, ...) であり,かつ引数に指定されたエンディアンと実行環境のエンディアンが異なる場合は, 変数に読み込んだ値に対して std::reverse() を適用してバイト列を反転させます.
Example
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include "clx/utility.h"
int main(int argc, char* argv[]) {
if (argc < 2) std::exit(-1);
std::fstream fs(argv[1]);
std::string s;
if (!clx::read(fs, s)) std::cout << "error: something is wrong." << std::endl;
else std::cout << "file size: " << s.size() << std::endl;
fs.clear(); // EOF フラグ等をクリア
fs.seekg(0);
char buf[256];
std::size_t n = clx::read(fs, buf);
if (n == 0) std::cout << "empty" << std::endl;
else std::cout << std::string(buf, std::min(n, sizeof(buf))) << std::endl;
return 0;
}
$ ./a example_istream_utility.cpp file size: 2470 /* ------------------------------------------------------------------------- */ /* * example_istream_utility.cpp * * Copyright (c) 2004 - 2010, clown. All rights reserved. * * Redistribution and use in source and binary forms, with or without
Functions
template <class Ch, class Tr, class Type, std::size_t N>
std::size_t read(std::basic_istream<Ch, Tr>& in, Type (&dest)[N],
int which = endian::none);
read() 関数テンプレートは,入力ストリームから最大 N * sizeof(Type) バイトのデータを dest に格納します.EOF に達した場合は,std::ios_base::eofbit をセットします. ストリームからデータが全く読み込まれなかった場合は,std::ios_base::failbit をセットします. 戻り値は in から読み込んだ要素数(バイト数ではない)です.
template <class Ch, class Tr, class Type, class Container>
std::basic_istream<Ch, Tr>& read(std::basic_istream<Ch, Tr>& in, Container& dest,
int which = endian::none);
read() 関数テンプレートは,入力ストリームから最大 max_size() * sizeof(Container::value_type) バイトのデータを dest に格納します.EOF に達した場合,std::ios_base::eofbit をセットします. EOF に達する前に max_size() に達した場合は,std::ios_base::failbit をセットします. また,ストリームからデータが全く読み込まれなかった場合も,std::ios_base::failbit をセットします. 戻り値は in です.
template <class Ch, class Tr, class Type, class Type>
std::basic_istream<Ch, Tr>& get(std::basic_istream<Ch, Tr>& in, Type& dest,
int which = endian::none);
get() 関数テンプレートは,入力ストリームから sizeof(Type) バイトのデータを dest に格納します. データが読み込まれなかった場合は,std::ios_base::failbit をセットします. EOF に達したためにデータが読み込まれなかった場合は,それに加えて std::ios_base::eofbit をセットします. 戻り値は in です.