nlib
misc/readfile/readfile.cpp

nn::nlib::FileInputStreamを利用してテキストファイルを読むサンプルです。 ファイルをオープンしてストリームから読み込みコンソールに表示します。

テキストはnn::nlib::TextReaderオブジェクトを通して読むことでUTF-8からUTF-32に変換されたものが利用可能です。 バイナリデータを直接読み込む場合はストリームオブジェクトを直接利用して読み込みます。

ファイル以外のストリームを利用して読み込む場合もそれぞれのストリームを利用すること以外は同様です。

#include <string>
NLIB_PATHMAPPER_FORSAMPLE
bool SampleMain(int, char**) {
// Initializes g_PathMapper which NLIB_PATHMAPPER_FORSAMPLE defines
InitPathMapperForSample();
// converts an URI to the corresponding native path
char filename[1024];
g_PathMapper.ResolvePath(NULL, filename, "nlibpath:///readonly/readfile.txt");
std::string str;
FileInputStream stream;
nlib_printf("Reading: \'%s\'\n", filename);
if (0 != stream.Init()) return false;
if (0 != stream.Open(filename)) return false;
TextReader reader;
reader.Init(&stream);
int c;
while ((c = reader.Read()) > 0) {
// The return value of TextReader::Read() is in UTF-32(UCS-4),
// but readfile.txt is in ASCII.
str += static_cast<char>(c);
}
if (reader.GetErrorValue() != 0) {
return false;
}
nlib_printf("%s", str.c_str());
return true;
}
NLIB_MAINFUNC