我正在尝试生成一个包含 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);
关于c++ - 生成文本文件时的额外字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513037/