Hi, why isn't this code is copying the file a.txt correctly?

int main()
{
	ifstream input("C://Users//Me//Desktop//a.txt");
	input.seekg (0, ios::end);
	int length = input.tellg();
	input.seekg (0, ios::beg);
	while(true)
	{
		char* buffer = new char[length];
		input.read(buffer, length);
		ofstream output("C://Users//Me//Desktop//b.txt");
		output.write(buffer, length);
		break;
	}
	return 0;
}

I attached a.txt and b.txt in a .zip file

delete that while loop -- no loop is necessary with the code you wrote because it reads and writes the entire file in one big swoop. That isn't practical for large files, but ok for fairly small ones.

And you need to open both files in binary mode -- just add ios::binary as second argument to the open function.

> ifstream input("C://Users//Me//Desktop//a.txt");
ONE forward /
or TWO backward \\

> while(true)
With a break statement at the end?
That's just trivial inline code, just delete all the control structure which you're not using.

Comments
Good Catch

Oh, I forgot about binary mode :|

Thanks for your helps guys--I appreciate it.
About the loop, it was just part of my program that I didn't comment out (I was planning on reading the file in chunks later).

It's working now.

This article has been dead for over six months. Start a new discussion instead.