nlib
misc/writefile/writefile.cpp

nn::nlib::FileOutputStreamを利用してテキストファイルを書くサンプルです。 ストリームを通して書いたファイルを読み込んでコンソールに表示します。

テキストはnn::nlib::TextWriterオブジェクトを通して書くことで UTF-16からUTF-8に変換されて書き込まれます。BOMは書き込まれません。 また、改行文字はCRLFに統一されます。

バイナリデータを直接書き込む場合はストリームオブジェクトを直接利用して書き込みます。

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

#include <string>
const wchar_t text[] =
L"Running in the circle is the green Yamanote line\n"
L"円く走るのが緑の山手線\n";
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:///readwrite/writefile.txt");
nlib_printf("Writing: \'%s\'\n", filename);
{
FileOutputStream stream;
// you can customize the buffer settings of FileOutputStream
// by specifying FileOutputStreamSettings as an argument for Init()
if (nlib_is_error(stream.Init())) return false;
if (nlib_is_error(stream.Open(filename))) {
nlib_printf("cannot open(w) file %s\n", filename);
return false;
}
{
// TextWriter writes UTF-8 string, converting UTF-16/UTF-32 into UTF-8.
// BOM is not written, and new line becomes CRLF.
TextWriter writer;
writer.Init();
writer.Open(&stream);
if (nlib_is_error(writer.Write(text))) return false;
}
// You have to Close() (File)OutputStream explicitly.
// You also have to check errors.
// It is because destructor cannot check any errors.
if (nlib_is_error(stream.Close())) return false;
}
std::string str;
FileInputStream stream;
// you can customize the buffer settings of FileInputStream
// by specifying FileInputStreamSettings as an argument for Init()
if (nlib_is_error(stream.Init())) return false;
if (nlib_is_error(stream.Open(filename))) {
nlib_printf("cannot open(r) file %s\n", filename);
return false;
}
// reads UTF-8 characters one by one from 'stream'
nlib_printf("Reading: \'%s\'\n", filename);
int c;
while ((c = stream.Read()) > 0) {
str += static_cast<char>(c);
}
if (nlib_is_error(stream)) {
return false;
}
nlib_printf("%s", str.c_str());
return true;
}
NLIB_MAINFUNC