2012-11-15 52 views
-2

可能重複:
Fastest way to find the number of lines in a text (C++)如何從一個文件中獲得的行數在C++

我有超過400.000行的文件。我在命令行中輸入文件名作爲輸入。將文件名稱轉換爲變量後,我試圖使用大小函數來查找文件的大小。我的代碼如下。但下面的代碼給了我錯誤的輸出。請讓我知道我哪裏錯了。

string input; 

// vector<string> stringList; 

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

TempNumOne = input.size(); 
+1

你並不實際打開該文件會出錯! – Rook

+0

我知道在SO上留下RTFM類型的回覆被認爲是不好的形式,但通過搜索很容易找到正確的方法。 [這](http://stackoverflow.com/questions/843154/fastest-way-to-find-the-number-of-lines-in-a-text-c)所以回答給出了一種可能性,但也許更多比你真正需要的複雜。 – Rook

回答

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讀取信息文件有關無實際上打開文件。

+0

您好,我需要獲取文件內的行數。不是物理大小。 – Teja

+0

@SOaddict:做一個'getline'計數循環! –

0

使用input.size(),你retreview輸入的大小。

如果你想得到檔案的大小,你必須打開檔案並使用seek。有關更多信息,請參閱this問題。

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; 
} 
+1

這會給你文件中的字節數,而不是行數。 –

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; 
} 
+0

當未使用的變量泄漏到環境範圍時,我總是感到有點不舒服... –

相關問題