0

我正在尝试生成一个包含 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 编译的。

4

2 回答 2

2

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

额外的字节来自每行的两个混合换行符 ( 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);
于 2015-09-10T23:27:19.230 回答
0

一些(Windows)编译器将“\n”替换为“\r\n”,所以如果你写“\r\n”,你会得到两次'\r'。

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

替换这一行:

file << "\r\n";

经过:

file << endl;
于 2015-09-10T23:37:37.823 回答