nlib
misc/writefile/writefile.cpp

This sample demonstrates the writing of text files using nn::nlib::FileOutputStream. It reads a file written via a stream and displays the content on the console.

Writing text through a nn::nlib::TextWriter object allows the text to be converted from UTF-16 to UTF-8 before being written. The BOM is not written. In addition, newline characters are integrated into CRLF.

To directly write binary data, direct use is made of a stream object for writing.

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

/*---------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)2012-2016 Nintendo. All rights reserved.
These coded instructions, statements, and computer programs contain
proprietary information of Nintendo of America Inc. and/or Nintendo
Company Ltd., and are protected by Federal copyright law. 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.
*---------------------------------------------------------------------------*/
#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