【问题标题】:How to read a file line by line or a whole text file at once?如何逐行读取文件或一次读取整个文本文件?
【发布时间】:2012-10-13 16:39:05
【问题描述】:

我在一个介绍文件的教程中(如何从文件中读取和写入文件)

首先,这不是作业,这只是我寻求的一般帮助。

我知道如何一次读取一个单词,但我不知道如何一次读取一行,或者如何读取整个文本文件。

如果我的文件包含 1000 个单词怎么办?逐字阅读整个文件是不切实际的。

我的名为“Read”的文本文件包含以下内容:

I love to play games
I love reading
I have 2 books

这是我迄今为止所取得的成就:

#include <iostream>
#include <fstream>

using namespace std;
int main (){
   
  ifstream inFile;
  inFile.open("Read.txt");

  inFile >>

有没有办法一次读取整个文件,而不是单独读取每一行或每个单词?

【问题讨论】:

  • 逐字阅读只比逐行慢一点。如果您确实需要单词,那么最好阅读单词。如果您正在处理面向行的数据(例如 CSV 文件),请读取行。
  • @Arkadiy 不正确。对于 100 MiB 的文件,逐行读取很容易需要几秒钟,而一次读取 4 KiB 的块则不到一秒。
  • @Vallentin:鉴于流都被缓冲,实际的磁盘读取已经逐块完成。剩下的只是在内存中操作数据。

标签: c++ iostream fstream file-handling


【解决方案1】:

你可以使用std::getline

#include <fstream>
#include <string>

int main() 
{ 
    std::ifstream file("Read.txt");
    std::string str; 
    while (std::getline(file, str))
    {
        // Process str
    }
}

另请注意,最好只在构造函数中使用文件名构造文件流,而不是显式打开(关闭也是如此,只需让析构函数完成工作即可)。

有关std::string::getline() 的更多文档可以在CPP Reference 阅读。

可能读取整个文本文件的最简单方法就是连接那些检索到的行。

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  

【讨论】:

  • 虽然不明显,但while(getline(f, line)) { ...} 确实是推荐的方法。此处对此进行了解释:gehrcke.de/2011/06/… --- 在那里您还可以找到正确处理错误的有用方法。
  • 没有#include &lt;iostream&gt;以上代码将无法编译
  • @Tyguy7 为什么需要#include &lt;iostream&gt;?在我看来&lt;fstream&gt;&lt;string&gt; 就足够了。如果你的意思是std::getline,它在&lt;string&gt;,而不是&lt;iostream&gt;
  • @FabioTurati 我不确定,我只知道一旦包含它,一切都编译好了。
【解决方案2】:

我知道这是一个非常古老的线程,但我还想指出另一种实际上非常简单的方法......这是一些示例代码:

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

int main() {

    ifstream file("filename.txt");
    string content;

    while(file >> content) {
        cout << content << ' ';
    }
    return 0;
}

【讨论】:

  • 不错的答案,我用它和 stringstream 而不是 cout 来将整个文件变成一个巨大的 stringstream
【解决方案3】:

我认为你可以使用 istream .read() 函数。您可以以合理的块大小循环并直接读取内存缓冲区,然后将其附加到某种任意内存容器(例如 std::vector)。我可以写一个例子,但我怀疑你想要一个完整的解决方案;如果您需要任何其他信息,请告诉我。

【讨论】:

  • 我不知道谁对这个答案投了反对票,但这很好,可能我不符合你的标准,但我使用相同的东西
【解决方案4】:

好吧,也可以使用C++中提供的freopen函数-http://www.cplusplus.com/reference/cstdio/freopen/逐行读取文件如下-:

#include<cstdio>
#include<iostream>

using namespace std;

int main(){
   freopen("path to file", "rb", stdin);
   string line;
   while(getline(cin, line))
       cout << line << endl;
   return 0;
}

【讨论】:

    【解决方案5】:

    另一种尚未提及的方法是std::vector

    std::vector<std::string> line;
    
    while(file >> mystr)
    {
       line.push_back(mystr);
    }
    

    然后您可以简单地遍历向量并修改/提取您需要的内容/

    【讨论】:

    • vector 是不必要的步骤。您可以使用std::istream_iterator&lt;std::string&gt;(inFile) 遍历ifstream
    【解决方案6】:

    上面的解决方案都很棒,但是“一次读取文件”还有一个更好的解决方案:

    fstream f(filename);
    stringstream iss;
    iss << f.rdbuf();
    string entireFile = iss.str();
    

    【讨论】:

      【解决方案7】:

      你也可以用它来一一读取文件中的所有行然后打印 i

      #include <iostream>
      #include <fstream>
      
      using namespace std;
      
      
      
      bool check_file_is_empty ( ifstream& file){
          return file.peek() == EOF ;
      }
      
      int main (){
      
      
          string text[256];
          int lineno ;
          ifstream file("text.txt");
          int num = 0;
      
          while (!check_file_is_empty(file))
          {    
              getline(file , text[num]);
              num++;
          }
          for (int i = 0; i < num ; i++)
          {
              cout << "\nthis is the text in " <<  "line " << i+1 << " :: " << text[i] << endl ;
      
      
          }
          
          system("pause");
      
          return 0;
      }
      

      希望这可以帮助你:)

      【讨论】:

        【解决方案8】:

        你好兄弟,这是一种使用此代码读取确切行中的字符串的方法

        希望对你有帮助!

        #include <iostream>
        #include <fstream>
        
        using namespace std;
        
        
        int main (){
        
        
            string text[1];
            int lineno ;
            ifstream file("text.txt");
            cout << "tell me which line of the file you want : " ;
            cin >> lineno ; 
        
        
        
            for (int i = 0; i < lineno ; i++)
            {
                
                getline(file , text[0]);
        
            }   
        
            cout << "\nthis is the text in which line you want befor  :: " << text[0] << endl ;
            system("pause");
        
            return 0;
        }
        

        祝你好运!

        【讨论】:

          【解决方案9】:

          下面的 sn-p 将帮助您读取由 unicode 字符组成的文件

          CString plainText="";
          errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
              if (0 == errCode)
              {
                  CStdioFile File(fStream);
                  CString Line;
                  while (File.ReadString(Line))
                  {
                      plainText += Line;
                  }
              }
              fflush(fStream);
              fclose(fStream);
          

          你应该总是在阅读后关闭文件指针,否则会导致错误

          【讨论】:

          • 由于使用了 CString,此答案不可移植
          • 使用,CString只包含头文件atlstr.h #include
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-04
          • 2017-08-06
          • 1970-01-01
          • 2015-05-13
          • 2020-09-11
          • 1970-01-01
          相关资源
          最近更新 更多