如何从C ++中获取文件中的行数

时间:2012-11-15 17:42:16

标签: c++ string filesize

  

可能重复:
  Fastest way to find the number of lines in a text (C++)

我有一个超过400.000行的文件。我在我的命令行输入文件名作为输入。将文件名转换为变量后,我试图使用size函数查找文件的大小。我的代码如下。但是下面的代码给了我错误的输出。请告诉我哪里出错了。

string input;

// vector<string> stringList;

cout << "Enter the file name :" <<endl;
cin >> input;//fileName;

TempNumOne = input.size();

4 个答案:

答案 0 :(得分:2)

这是标准的习语:

#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)来读取关于文件的信息,而无需实际打开文件

答案 1 :(得分:0)

使用input.size(),您可以重新查看输入字符串的大小。

如果您想获得文件的大小,则必须打开该文件并使用seek。有关更多信息,请参阅this问题。

答案 2 :(得分:0)

正如Rook所说,你需要打开一个文件才能看到它的内容。现在,当你调用input.size()时,它会给你文件名的长度。

这是一种做你想做的事的简单方法:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
//get file name (use C string instead of C++ string)
char fileName [1000];
cout << "Enter the file name :" << endl;
cin.getline(fileName, 1000); // this can hendle file names with spaces in them

// open file
ifstream is;
is.open(fileName);

// get length of file
int length;
is.seekg (0, ios::end);
length = is.tellg();

cout << fileName << "'s size is " << length << endl;

return 0;
}

答案 3 :(得分:0)

代码:

#include <fstream>
#include <string>
#include <iostream>

int main() 
{ 
    int Rows = 0;
    std::string line;
    std::string filename;

    std::cout << "Enter file> ";
    std::cin>>filename;
    std::fstream infile( filename.c_str() );

    while (std::getline(infile, line))    ++Rows;
    std::cout << "" << Rows<<" rows in the file\n\n";

    return 0;
}
相关问题