-1
Is there any function that copies a txt file to disk and transfers it whole to a string, without copying character by character in c++?
-1
Is there any function that copies a txt file to disk and transfers it whole to a string, without copying character by character in c++?
3
Exactly as you’re talking you don’t have, but something close does. It actually has a set of tools for accessing files. You must study and master them all to ride the way you wish.
Behold ifstream
.
2
You can create an instance of std::string
from a std::ifstream
, look at you:
#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 in 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;
}
Thanks, I need to study more #include <streambuf>, but in the excerpt that code you posted, can understand
Browser other questions tagged c++
You are not signed in. Login or sign up in order to post.
I don’t understand java , I’m studying a code to compress files in java and I saw that in java there is a faster tool to do what I said above. using the ifstream library I can copy character to character, I thought there was a more effective way. Anyway thank you
– Andre Luiz
Actually, it’s just that you didn’t want to study what I gave you, that’s not what you’re talking about. I can assure you that you can not copy more efficiently in Java (also the difference will be tiny), just have something more ready to use.
– Maniero
okk , I’m studying this right now!! but anyway thank you!
– Andre Luiz