使用C ++将文件内容读入字符串 [英] Read file-contents into a string in C++
本文介绍了使用C ++将文件内容读入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ b $ b
在Perl这样的脚本语言中,可以一次读取一个文件到变量中。
open(FILEHANDLE,$ file);
$ content =< FILEHANDLE> ;;
在C ++中最有效的方法是什么?
解决方案
像这样:
#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;
}
语句
std :: string content((std :: istreambuf_iterator< char>(ifs)),
(std :: istreambuf_iterator< char&
可分为
std :: string content;
content.assign((std :: istreambuf_iterator< char>(ifs)),
(std :: istreambuf_iterator< char>()))
这很有用,如果你想覆盖现有的std :: string变量的值。 / p>
Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?
In scripting languages like Perl, it is possible to read a file into a variable in one shot.
open(FILEHANDLE,$file);
$content=<FILEHANDLE>;
What would be the most efficient way to do this in C++?
解决方案
Like this:
#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;
}
The statement
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
can be split into
std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
which is useful if you want to just overwrite the value of an existing std::string variable.
这篇关于使用C ++将文件内容读入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文