باستخدام FileStreams C ++ (Ftream)، كيف يمكنك تحديد حجم الملف؟ [مكرر

StackOverflow https://stackoverflow.com/questions/2409504

  •  18-09-2019
  •  | 
  •  

سؤال

هذا السؤال لديه بالفعل إجابة هنا:

أنا متأكد من أنني فاتني ذلك فقط في الدليل، ولكن كيف يمكنك تحديد حجم الملف (في البايتات) باستخدام 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.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top