わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

指定したファイルをstringに読み込む

ifstreamで読み取ったデータをファイルの終端までstringにinsertしていきます。

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
#include <locale.h>
#include <fstream>



/*
	指定したファイルをstringに読み込む
*/
std::string ReadStringFromFile
(
	std::wstring oPath
)
{
	std::ifstream oIfstream( oPath.c_str() );
	std::string oResultString;

	// ファイルのオープン確認
	if ( oIfstream.is_open() ) {

		// read file
		const std::size_t blockSize = 1024 * 1024;

		// バッファの確保
		char* cpBuf = new char[ blockSize ];
		if ( NULL != cpBuf ) {

			// 読み出したサイズ
			int nReadByte = 0;

			// ブロック単位で読み出し
			while ( ( nReadByte = oIfstream.read( cpBuf, blockSize ).gcount() ) > 0) {

				// 文字列追加
				oResultString.insert( oResultString.size(), cpBuf, nReadByte );
			}

			// バッファの解放
			delete [] cpBuf;
		}
	}

	// 読み込んだ内容を返す
	return( oResultString );
}



int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	// 標準出力にユニコード出力する
	setlocale( LC_ALL, "Japanese" );

	// 指定したファイルをstringに読み込む
	std::string oString = ReadStringFromFile( L"test_file.txt" );

	// 標準出力へ出力する
	std::cout << oString << std::endl;

	// 正常終了
	return( 0 );
}

実行結果

ファイルの内容です。






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。