わびさびサンプルソース

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

ファイルを読み込む

ifstreamのreadメソッドファイルを読み込みます。この時に読み込まれたファイルのデータ量は、ifstreamのgcountメソッドで取得できます。

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



/*
	ファイルの読み込み
*/
int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	// 標準出力にユニコード出力する
	setlocale( LC_ALL, "Japanese" );

	/*
		ファイルの読み込み
	*/
	{
		std::string strFile;

		// ファイルのオープン
		std::ifstream ifstr( L"file.txt", std::ios::in | std::ios::binary );
		if ( !ifstr ) {

			// ファイルがオープンできなかった
			std::wcout << L"ファイルオープン失敗" << std::endl;
			return( - 1);
		}

		int nBufferSize = 1024;

		// バッファの確保
		char* pBuf = new char[ nBufferSize];

		/*
			ファイルの最後まで読み込み
		*/
		while( !ifstr.eof() ) {

			// ファイルを読み込む
			ifstr.read( pBuf, nBufferSize );

			// 読み込んだサイズだけ文字列へ追加
			strFile.append( pBuf, ifstr.gcount() );
		}

		// バッファの破棄
		delete pBuf;

		// 標準出力へ出力
		std::cout << strFile.c_str() << std::endl;
	}

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

実行結果

ファイルを読みこみました






わびさびサンプルソース

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