Update:
resolved in here: https://stackoverflow.com/a/145309/15603477
https://www.cplusplus.com/reference/ostream/ostream/write/
example not working as i intended. I have 2 files(test.txt, new.txt) in the same directory/folder as main.cpp.
new.txt is empty file. test.txt have one line: https://www.cplusplus.com/reference/ostream/ostream/write/
when I run it, it says: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
This example copies a file into memory and then writes its content to a new file. But it now have an error.
std::ifstream infile ("test.txt",std::ifstream::binary);
std::ofstream outfile ("new.txt",std::ofstream::binary);
// get size of file
infile.seekg (0,infile.end);
long size = infile.tellg();
infile.seekg (0);
// allocate memory for file content
char* buffer = new char[size];
// read content of infile
infile.read (buffer,size);
// write to outfile
outfile.write (buffer,size);
// release dynamically-allocated memory
delete[] buffer;
outfile.close();
infile.close();
update about path:
after add line std::cout << "Current path is " << fs::current_path() << '\n'; // (1)
It shows: Current path is "C:\\Users\\JIAN HE\\CLionProjects\\stl\\cmake-build-debug"
but current text.txt is C:\Users\JIAN HE\CLionProjects\stl.
update2:
problem solved. Put both file to cmake-build-debug directory.