0

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

4
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by CppFTW
0

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.

1

> 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.

Votes + Comments
Good Catch
0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.