• Advertisement

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

This topic is 4920 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

##### Share on other sites
Advertisement
Quote:
 Original post by ThatIsToSayThatAt 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

##### Share on other sites
Quote:
Original post by Leffe
Quote:
 Original post by ThatIsToSayThatAt 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

##### Share on other sites

• Advertisement
• Advertisement
• ### Popular Tags

• Advertisement
• ### Popular Now

• 10
• 14
• 11
• 10
• 11
• Advertisement