Everywhere for some reason only the reverse operation is described.

ofstream openFile; string saveFile; openFile.open("D:\\sites\\accounts.txt", ios::in); // saveFile = openFile.str(); openFile.close(); 

3 answers 3

A few more options (in theory, ascending speed):

 std::string readFile(const std::string& fileName) { return std::string((std::istreambuf_iterator<char>(std::ifstream(fileName))), std::istreambuf_iterator<char>()); } 
 std::string readFile(const std::string& fileName) { std::ifstream f(fileName); std::stringstream ss; ss << f.rdbuf(); return ss.str(); } 
 std::string readFile(const std::string& fileName) { std::ifstream f(fileName); f.seekg(0, std::ios::end); size_t size = f.tellg(); std::string s(size, ' '); f.seekg(0); f.read(&s[0], size); // по стандарту можно в C++11, по факту работает и на старых компиляторах return s; } 
  • the last variant is bad - why fill the string with spaces (std :: string s (size, '')), when you can simply do .resize ()? - gbg
  • @gbg can be resize , the difference is that resize will require memory reallocation, and the fill constructor (most likely) will immediately request the necessary piece. In other words, resize potentially slower. - Vladimir Gamalyan
  • In the case of taking the finished string immediately, we get a long and sad blocking with zeros of the selected block. - gbg
  • @gbg you are surprised, but resize does the same thing (scores with zeros) - Vladimir Gamalyan
  • You are surprised, but the resize constructor does not call stackoverflow.com/a/7413968/5533854 - gbg

For a start, ofstream intended for output to a file, for input from a file use ifstream . The easiest way to read is line by line:

 std::ifstream file("тут ваш путь"); std::string line; while (std::getline(file, line)) { // обработайте строку // например, добавьте её к суммарной строке } 

Do not forget that std::getline does not save \n at the end of the line, so if necessary add it yourself.

     #include <iostream> #include <fstream> #include <string> bool readfile(std::string& s, const char* filename){ std::ifstream fp(filename); if(! fp.is_open()) return false; char nil = '\0'; std::getline(fp, s, nil); fp.close(); return (s.length() > 0); } int main(void){ std::string s; if(readfile(s, "file.txt")) std::cout << s << std::endl; return 0; }