わびさびサンプルソース

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

ファイルサイズの取得

tellg()関数を利用してファイルサイズを取得します。ファイルサイズの取得には、 一旦ファイルの最後まで、seekg()関数でファイルポインタを移動してから、 tellg()関数で現在のファイルポインタ位置を取得する事によって取得します。

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



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

	std::ifstream ifstr( L"file.txt" );

	// 一番最後までseek
	ifstr.seekg( 0, std::ios_base::end );

	// 現在のポインタ位置取得
	int filesize = ifstr.tellg();

	// 一番先頭までseek
	ifstr.seekg( 0, std::ios_base::beg );

	// ファイルサイズを表示
	std::wcout << L"ファイルサイズは" << filesize << L"バイトです。" << std::endl;

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

実行結果

ファイルサイズは1024バイトです。






わびさびサンプルソース

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