nlib
misc/writefile/writefile.cpp

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

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

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

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

/*--------------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)Nintendo All rights reserved.
These coded instructions, statements, and computer programs contain proprietary
information of Nintendo and/or its licensed developers and are protected by
national and international copyright laws. They may not be disclosed to third
parties or copied or duplicated in any form, in whole or in part, without the
prior written consent of Nintendo.
The content herein is highly confidential and should be handled accordingly.
*--------------------------------------------------------------------------------*/
#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