copy an entire txt file to a string in c ++

-1

Is there a function that copies a txt file to disk and transforms it into a string, without copying character by character in c ++?

    
asked by anonymous 02.07.2018 / 02:17

2 answers

2

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;
}
    
02.07.2018 / 04:08
3

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 .

    
02.07.2018 / 02:21