简体   繁体   English

使用C ++和Linux写入文件

[英]Writing to a file with C++ and Linux

I have to implement a buffered writer with C++ on linux. 我必须在Linux上用C ++实现一个缓冲编写器。 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). 现在我有一个问题:我可以向文件中写入字符,但是除此之外,文件中还填充有无效字符(在gedit中,文件中的真实字符后填充了\\ 00)。

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 eg with whitespaces, it all works fine, but is there another way to prevent the "invalid characters"? 当我用空白初始化缓冲区时,一切正常,但是还有另一种防止“无效字符”的方法吗?

Thanks for helping me 谢谢你帮我

Because you're using O_DIRECT , you're apparently forced to write in pagesize increments. 因为您使用的是O_DIRECT ,所以您显然被迫以pagesize增量进行写入。 However, that implies your file will always be padded out to a multiple of pagesize . 但是,这意味着您的文件将始终被填充为pagesize的倍数。 In your current code, it will be padded with zeros, because you zero the page each time before filling it. 在您当前的代码中,将用零填充,因为您每次在填充页面之前会将页面归零。

One way to address this is to track the actual amount of data that should be in the file, and ftruncate() the file to the desired size before closing it. 解决此问题的一种方法是跟踪文件中应包含的实际数据量,并在关闭文件之前将文件ftruncate()调整为所需大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM