C++ ファイルストリーム (fstream) を使用して、ファイルのサイズをどのように判断できますか?[重複]
質問
この質問にはすでに答えがあります:
マニュアルでこれを見逃しただけだと思いますが、C++ を使用してファイルのサイズ (バイト単位) を確認するにはどうすればよいですか? istream
からのクラス fstream
ヘッダ?
解決
あなたはios::ate
フラグ(とios::binary
フラグ)を使用してファイルを開くことができますので、tellg()
機能はあなたに直接ファイルのサイズが得られます。
ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();
他のヒント
あなたはその後、差異を計算し、最後まで追求することができます:
std::streampos fileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}
ファイルの正確なサイズを決定するためにtellg
を使用しないでください。 tellg
によって決定される長さは、文字の数は、ファイルから読み込むことができるよりも大きくなる。
stackoverflowの質問から tellg()関数でファイルの間違ったサイズを与えます? tellg
は、ファイルのサイズを報告しません、またバイト単位で先頭からのオフセット。これは、後で同じ場所、そして何よりもに求めるために使用することができますトークン値を報告します。 (それも、あなたは整数型に形を変えることができるという保証はありません。)。 Windowsの(そしてほとんどの非Unixシステム)の場合は、テキストモードでは、戻り、あなたがその位置に到達するために読まなければならないバイト数をtellg何の間には直接的かつ即時のマッピングがありません。
、確実にそうすることの唯一の方法は、読むことです。あなたが好きなものでこれを行うことができる必要があります:
#include <fstream>
#include <limits>
ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );
このよう
long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;
私は初心者だけど、これはそれをやって私の独学の方法です。
ifstream input_file("example.txt", ios::in | ios::binary)
streambuf* buf_ptr = input_file.rdbuf(); //pointer to the stream buffer
input.get(); //extract one char from the stream, to activate the buffer
input.unget(); //put the character back to undo the get()
size_t file_size = buf_ptr->in_avail();
//a value of 0 will be returned if the stream was not activated, per line 3.
所属していません StackOverflow