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(); 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; } 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 Gamalyanresize does the same thing (scores with zeros) - Vladimir GamalyanFor 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; } Source: https://ru.stackoverflow.com/questions/527567/
All Articles