Sign in to follow this  
ThatIsToSayThat

My file-copy program appends a NULL character for each newline

Recommended Posts

Hey there, I made this simple C++ program which was supposed to copy text files one character at a time. When I copy a single-line file, it works as expected. But when I copy a file that does contain newlines, a NULL character is appended to the end of the file for each newline that was present in the original file. The characters are visible as little squares. For example, source.txt ---------- This is line 1. This is line 2. This is line 3. copied.txt ---------- This is line 1. This is line 2. This is line 3.[NULL][NULL] The relevant code is in the function copyFile():
#include <fstream>

void copyFile(const char *source, const char *destination)
{
	// read source file
	std::ifstream inStream(source, std::ios::in | std::ios::nocreate);
	inStream.seekg(0, std::ios::end);
	long length = inStream.tellg();
	inStream.seekg(0, std::ios::beg);
	char *buffer = new char[length];
	char *currentCharacter = buffer;
	for (int i = 0; i < length; i++, currentCharacter++)
	{
		inStream.read(currentCharacter, sizeof(char));
	}
	inStream.close();

	// write destination file
	std::ofstream outStream(destination, std::ios::out | std::ios::noreplace);
	outStream.write(buffer, sizeof(char) * length);
	outStream.close();

	delete [] buffer;
}


At first I thought this might have to do with the way newlines are represented in text files vs. in C++, but after messing around with it a bit I'm not so sure. What's causing the problem? Thanks.

Share this post


Link to post
Share on other sites
Quote:
Original post by ThatIsToSayThat
At first I thought this might have to do with the way newlines are represented in text files vs. in C++, but after messing around with it a bit I'm not so sure. What's causing the problem?


My first thought too, try reading/writing the files in binary mode instead. Adding ios::binary should do the trick?

Share this post


Link to post
Share on other sites
Quote:
Original post by Leffe
Quote:
Original post by ThatIsToSayThat
At first I thought this might have to do with the way newlines are represented in text files vs. in C++, but after messing around with it a bit I'm not so sure. What's causing the problem?


My first thought too, try reading/writing the files in binary mode instead. Adding ios::binary should do the trick?

Agh, you got it. I guess it makes sense that if I'm using lower-level functions like read() and write() rather than operator<< and operator>>, I should use binary mode for the file streams instead of plain ASCII mode. Thanks for helping.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this