Search code examples
c++fileifstreamistreamstd

What is the preferred way to read from a file into a char array?


Apologies for the basic question; I'm relatively new to C++.

I've looked around and seen many different suggestions for how to read from a file to a char array. For example, this one creates a char array of size 10000, but this is suboptimal (either wasted space, or not enough space).

What's the simplest, and most commonly used method for reading from a file to a string, or string-like sequence? This is such a common operation; there's got to be a standard way to do it. Is there no one-liner for this?


Solution

  • I would use this usually (like when we're not reading thousands of files in a loop!):

    std::ifstream file("data.txt"); 
    std::string data {std::istreambuf_iterator<char>{file}, 
                      std::istreambuf_iterator<char>{} };
    

    No need to use std::copy (like the other answer; now deleted!).

    If you want vector, then use this instead:

    std::vector<char> data {std::istreambuf_iterator<char>{file}, 
                            std::istreambuf_iterator<char>{} };
    

    However, if you want to populate an existing std::vector (or std::string), then use insert method (both types has insert method of same signature!):

    data.insert(data.end(),                           //insert at end
                std::istreambuf_iterator<char>{file}, //source begin
                std::istreambuf_iterator<char>{} );   //source end
    

    Hope that helps.