生成文本文件时的额外字节

Extra bytes when generating text file

我正在尝试生成一个包含 50 行的文本文件,每行包含 50 个空格。但是,每隔几行,文件中就会添加 9 或 10 个额外字节。

#include <iostream>
#include <fstream>
using namespace std;

void InitializeCanvas() {
    ofstream file("paint.txt");
    int b = 0;
    for (int i = 0; i < 50; i++) {
        for (int j = 0; j < 50; j++) {
            file << " ";
        }
        file << "\r\n";

        //these lines show where the pointer is and where it should be
        b += 52;
        int pointer = file.tellp();
        int difference = pointer - b;
        cout << pointer << " (" << (difference) << ")" << endl;
    }
    file.close();
}

int main() {
    InitializeCanvas();
    return 0;
}

在第 9 行,添加了 9 个额外的字节。在第 19 行,有 19 个额外的字节。 29、39 和 49 相同。除了这些行外,没有添加额外的字节。是什么原因造成的?此代码是使用 CodeBlocks 13.12 编译的。

编辑:由于问题得到了一些额外的信息,这个答案的解释不再完全适合 - 但解决方案应该有效。

额外的字节来自每行两个混合换行符 (NL+CRLF)。让我们看一下一行的结尾,因为 \n 在你的编译器中已经被解释为 \r\n

...  20     0D   0D   0A
... Space   NL   CR   LF

解决方案在ofstream的构造函数中。它处于文本模式。

explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);

只需使用\n或以二进制格式写入数据,或使用endl

ofstream file("paint.txt", std::ios_base::binary | std::ios_base::out);

一些 (windows) 编译器将“\n”替换为“\r\n”,因此如果您编写“\r\n”,您会得到两次“\r”。

您需要做的就是使用 endl 而不是 "\r\n"

替换此行:

file << "\r\n";

作者:

file << endl;