我需要获得(i)stringstream / ifstream大小。我在更多地方使用代码,所以我为它编写了一个函数。该功能需要istream&作为参数(因此它更通用)。代码使用seekg到流的末尾,看起来像这样:
#include <iostream>
#include <sstream>
#include <fstream>
std::streamsize getStreamSize(std::istream& is) {
const std::streampos currentPos{ is.tellg() };
const std::streamsize size{ is.seekg(0, std::ios::end).tellg().seekpos() };
is.seekg(currentPos);
return size;
};
int main()
{
using namespace std;
string s{ "some string" };
cout << "string: " << s << endl;
istringstream ss{ s };
istream& is{ ss };
streampos size{ is.seekg(0, ios::end).tellg() };
cout << "stream size: " << size << endl;
cout << "stream size reference: " << getStreamSize(is) << endl;
cout << "stream size reference: " << getStreamSize(ss) << endl;
ifstream ifs{ "some_file_path.txt" };
cout << "file stream size: " << getStreamSize(ifs) << endl;
return 0;
}
此代码的输出如下:
string: some string
stream size: 11
stream size reference: 0
stream size reference: 0
file stream size: 6021120
为什么不可能得到(i)通过引用传递的字符串流大小,但是可以获得本地引用的i(stringstream)大小或通过引用传递的ifstream?
Windows 10,SDK版本10.0.16299.0,Visual Studio Community 15.4.2