下面是標準的成語:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename;
if (!(std::cout << "Enter filename: " &&
std::getline(std::cin, filename)))
{
std::cerr << "Unexpected input error!\n";
return 0;
}
std::ifstream infile(filename.c_str()); // only "filename" in C++11
if (!infile)
{
std::cerr << "File '" << filename << "' could not be opened!\n";
return 0;
}
infile.seekg(0, std::ios::end);
std::size_t fs = infile.tellg();
infile.seekg(0, std::ios::beg);
std::size_t count = 0;
for (std::string line; std::getline(infile, line); ++count) { }
std::cout << "File size: " << fs << ". Number of lines: " << count << ".\n";
}
如果你願意使用特定於平臺的代碼(如POSIX),可以使用目錄查詢功能,如lstat
讀取信息文件有關無實際上打開文件。
你並不實際打開該文件會出錯! – Rook
我知道在SO上留下RTFM類型的回覆被認爲是不好的形式,但通過搜索很容易找到正確的方法。 [這](http://stackoverflow.com/questions/843154/fastest-way-to-find-the-number-of-lines-in-a-text-c)所以回答給出了一種可能性,但也許更多比你真正需要的複雜。 – Rook