Is there a function that copies a txt file to disk and transforms it into a string, without copying character by character in c ++?
Is there a function that copies a txt file to disk and transforms it into a string, without copying character by character in c ++?
You can create an instance of std::string
from a std::ifstream
, see:
#include <iostream>
#include <string>
#include <fstream>
#include <streambuf>
using namespace std;
int main( void )
{
/* Abre Arquivo texto para leitura */
ifstream ifs("arquivo.txt");
/* Constroi string */
string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());
/* Exibe string */
cout << str << endl;
return 0;
}
Simplifying a single function:
#include <iostream>
#include <string>
#include <fstream>
#include <streambuf>
using namespace std;
string ler_arquivo( const string& arq )
{
ifstream ifs(arq.c_str());
string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());
return str;
}
int main( void )
{
string str = ler_arquivo( "arquivo.txt" );
cout << str << endl;
return 0;
}
Exactly as you are saying, there is nothing but something close. It actually has a set of tools for accessing files. You need to study and master all of them to put it together the way you want it.
See ifstream
.