I have to implement a buffered writer with C++ on linux. Now I've got a problem: I can write characters to a file, but in addition, the file is filled with invalid characters (in gedit the file is filled with \00 after the real characters).
Here's a part of the code:
BufferedWriter::BufferedWriter(const char* path) {
pagesize = getpagesize();
if ((fd = open(path, O_WRONLY | O_DIRECT | O_CREAT | O_TRUNC, S_IRWXU))
== -1) {
perror("BufferedWriter: Error while opening file");
throw -1;
}
if (posix_memalign((void**) &buffer, pagesize, pagesize) != 0) {
perror("BufferedWriter: Error while allocating memory");
throw -3;
}
for (int i = 0; i < pagesize; i++) {
buffer[i] = 0;
}
charCnt = 0;
}
...
void BufferedWriter::writeChar(char c) {
buffer[charCnt] = c;
charCnt++;
if (charCnt == pagesize) {
if (write(fd, buffer, pagesize) == -1) {
perror("BufferedWriter: Error while writing to file");
throw -5;
}
for (int i = 0; i < pagesize; i++) {
buffer[i] = 0;
}
charCnt = 0;
}
}
When I initialize my buffer e.g. with whitespaces, it all works fine, but is there another way to prevent the "invalid characters"?
Thanks for helping me