#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;
}
My file-copy program appends a NULL character for each newline
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():
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.
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?
Quote:Original post by LeffeQuote: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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement