代码之家  ›  专栏  ›  技术社区  ›  Babiker

C++读取文件

c++
  •  0
  • Babiker  · 技术社区  · 15 年前

    在C++中读取文件并将其内容分配给字符串所需的最小代码是多少? 我确实读了很多有用的教程,但它们在某种程度上都不同,所以我想知道为什么,所以如果你能包括一些解释性的评论,那就太好了。


    相关: What is the best way to read an entire file into a std::string in C++?

    7 回复  |  直到 15 年前
        1
  •  2
  •   Michael Kristofik    15 年前
    #include <fstream>
    #include <string>
    
    int main()
    {
        std::ifstream file("myfile.txt");  // open the file
        std::string line, whole_file;
    
        // Read one line at a time from 'file' and store the result
        // in the string called 'line'.
        while (std::getline(file, line))
        {
            // Append each line together so the entire file will
            // be in one string.
            whole_file += line;
            whole_file += '\n';
        }
    
        return 0;
        // 'file' is closed automatically when the object goes out of scope.
    }
    

    这里有几点需要注意。 getline() 返回对stream对象的引用,如果发生任何错误或到达文件结尾,则在while测试失败。另外,后面的换行符是 包含在字符串中,因此必须手动附加它。

        2
  •  3
  •   Community datashaman    7 年前

    似乎是复制品:

    How do you get a file in C++?

    无论如何,一个好的参考: http://www.cplusplus.com/doc/tutorial/files/

        3
  •  2
  •   Loki Astari    15 年前

    最短的代码:(不有效)

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <iterator>
    #include <fstream>
    
    int main()
    {
        std::ifstream f("plop");
    
    
        std::string buffer;
        std::copy(std::istreambuf_iterator<char>(f),
                  std::istreambuf_iterator<char>(),
                  std::back_inserter(buffer));
    }
    

    我可能会怎么做:

    #include <iostream>
    #include <string>    
    #include <vector>
    #include <algorithm>
    #include <iterator>
    #include <fstream>
    
    
    
    int main()
    {
        // Find the size of the file
        std::ifstream       file("Plop");
        file.seekg(0,std::ios_base::end);
    
        std::streampos      size    = file.tellg();
    
        // Read the file in one go.
        file.seekg(0);
        std::vector<char>   buffer(size); // pre-szie the vector.
        file.read(&buffer[0],size);
    
        // or
    
        // Until the next version of the standard I don't think string gurantees contigious storage.
        // But all the current versions I know do use continious storage so it should workd.
        file.seekg(0);
        std::string         buffer1(size);
        file.read(&buffer1[0],size);
    }
    
        4
  •  2
  •   YeahStu    15 年前

    我没有看到那么多:

    #include <fstream>
    #include <sstream>
    #include <string>
    using namespace std;
    
    int main() {
        ifstream ifs("filename");
        stringstream ss;
        ss << ifs.rdbuf();
        string s = ss.str();
    }
    

    …正如我所料。你也需要一些错误检查。

    康拉德·鲁道夫将此作为上述“相关问题”的答案。我想这不是重复的,因为这要求最短的代码,但是答案是相同的。所以我把它作为维基转载到这里。

        5
  •  1
  •   Syed Tayyab Ali    15 年前

    我在每行读一个词。

        #include<fstream>
        #include<string>
        using namespace std;    
        int main(int argc, char **argv)
        {
        fstream inFile;
        string str;
        while(!inFile.eof())
        {
        inFile.open("file.txt");
        infile>>str;
        }
        inFile.close();
        return 0;
        }
    
        6
  •  0
  •   anon    15 年前

    这比简短的解决方案要长,但可能会稍微提高效率,因为它的复制工作要少一点——不过,我还没有进行任何时间比较:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    using namespace std;;
    
    unsigned int FileRead( istream & is, vector <char> & buff ) {
        is.read( &buff[0], buff.size() );
        return is.gcount();
    }
    
    int main() {
        ifstream ifs( "afile.dat", ios::binary );
        const unsigned int BUFSIZE = 64 * 1024; 
        std::vector <char> buffer( BUFSIZE );
        unsigned int n;
        string s;
        while( n = FileRead( ifs, buffer ) ) {
            s.append( &buffer[0], n );
        }
    
        cout <<  s;
    }
    
        7
  •  0
  •   dcw    15 年前

    如果你 知道 您的文件包含文本,然后您可以使用 STLSoft platformstl::memory_mapped_file :

    platformstl::memory_mapped_file file("your-file-name");
    std::string contents(static_cast<char const*>(file.memory()), file.size());
    

    platformstl::memory_mapped_file file("your-file-name");
    std::wstring contents(static_cast<wchar_t const*>(file.memory()), 
              file.size() / sizeof(wchar_t));
    

    在Windows上,这将使字符串包含 \r\n 序列,因此您可以使用 winstl::load_text_file() 功能:

    std::string contents;
    winstl::load_text_file("your-file-name", contents);
    

    如果要将其加载到行集合中,请使用 platformstl::read_lines() :

    platformstl::basic_file_lines<char> lines("your-file-name");
    size_t n = lines.size();
    std::string line3 = lines[3];