Efficiently Reading File Contents into a String in C
In C , unlike scripting languages such as Perl, reading the entire contents of a file into a string in a single operation is not directly available. However, there are efficient methods to achieve this functionality.
To read file contents into a string, we can utilize C 's file input handling capabilities. Here's an efficient solution:
<code class="cpp">#include <fstream> #include <string> int main(int argc, char** argv) { std::ifstream ifs("myfile.txt"); std::string content( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); return 0; }</code>
The code uses an input file stream to read the contents of the file named "myfile.txt" and stores them in a string variable named "content." The expression used to assign the file contents to the string is:
<code class="cpp">std::string content( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) );</code>
This expression utilizes iterators to read character by character from the input file stream and constructs the string. The first iterator is initialized with the input file stream, while the second iterator is a default constructed "end" iterator, indicating the end of the file.
Alternatively, you can use the following code to overwrite the value of an existing string variable:
<code class="cpp">std::string content; content.assign( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) );</code>
This code overwrites the value of the existing string variable "content" with the contents of the file.
The above is the detailed content of How can I efficiently read the entire contents of a file into a string in C ?. For more information, please follow other related articles on the PHP Chinese website!