nlib
misc/readfile/readfile.cpp

This sample demonstrates reading text files using nn::nlib::FileInputStream. It opens a file, reads from the stream, and displays the content to the console.

The text is read via a nn::nlib::TextReader object, enabling the use of data converted from UTF-8 to UTF-32. To directly read binary data, direct use is made of a stream object for reading.

The process is the same when streams other than file streams are used for reading; the only difference is the stream being used.

#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 (nlib_is_error(stream.Init())) return false;
if (nlib_is_error(stream.Open(filename))) return false;
TextReader reader;
reader.Init();
reader.Open(&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 (nlib_is_error(reader)) {
return false;
}
nlib_printf("%s", str.c_str());
return true;
}
NLIB_MAINFUNC