2015-12-16 46 views
3

我正在嘗試編寫一個程序來打印最後一行文件,並且我想出了以下內容。我在文件中的位置SEEKs,但是此代碼在無限循環中運行。如果我註釋掉(1)並啓用(2),則代碼正常工作。我無法弄清楚原因。在ifstream getlines [耗盡文件]後seekg問題

#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::string line; 
    int count = 0; 
    long int seek_length = -1l;// should be -100l 
    std::ifstream ifile("D:\\cprog\\test.csv");// --(1) 
    while(true){ 
     seek_length *= 2; 
     count = 0; 
     //std::ifstream ifile("D:\\cprog\\test.csv"); //-- (2) 
     ifile.seekg(seek_length, std::ios_base::end); 
     while(std::getline(ifile,line)){ 
      ++count; 
     } 
     if(count > 1) 
      break; 
    } 
    std::cout << line << '\n'; 
} 

編譯:G ++(GCC)4.9.2(MINGW)

+0

可怕的標題。讓標題描述問題。 –

回答

3

您需要再次閱讀之前清除您的流的錯誤狀態:

ifile.clear(); 

否則,它第一次遇到EOF,流將進入錯誤狀態,並且所有後續讀取都將失敗。

請注意,如果你這樣做,而你的文件只包含1(或0)行,你現在的代碼將永遠循環。

+0

是啊..'小心,如果你這樣做,而你的文件只包含1(或0)行,你現在的代碼形式將永遠循環。「需要考慮它。 – gjha

0

最終工作代碼如下,可以通過以下方式之一解決問題。

#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::string line; 
    int count = 0; 
    long int seek_length = -100l; 
    std::ifstream ifile("D:\\cprog\\test.csv"); 
#if 0 
    while(true){ 
     seek_length *= 2; 
     count = 0; 
     ifile.seekg(seek_length, std::ios_base::end); 
     if(ifile.tellg() < 0){ 
      ifile.clear(); 
      ifile.seekg(0l, std::ios_base::beg); 
      while(std::getline(ifile,line)); 
      break; 
     } 
     else 
     { 
      while(std::getline(ifile,line)){ 
       ++count; 
      } 
      if(count > 1) 
       break; 
     } 
     ifile.clear(); 
    } 
#else 
    char ch; 
    ifile.seekg(0l, std::ios_base::end); 
    do 
    { 
     ch = ifile.peek(); 
     ifile.seekg(-1l, std::ios_base::cur); 
     std::cout << ch <<'~' << ifile.tellg() <<'\n'; 
    }while(ch != '\n' && ifile.tellg() > -1); 
    if(ifile.tellg() < 0) 
     ifile.seekg(0l, std::ios_base::beg); 
    else 
     ifile.seekg(2l, std::ios_base::cur); 
    ifile.clear(); 
    std::getline(ifile,line); 
#endif 
    if(line.empty()) 
     std::cout<<"------- EMPTY LINE -----\n"; 
    else std::cout << line << '\n'; 
}