C++将字符串写入文件 = 额外字节
我正在使用 C++ 来查看 256 个计数并将 ASCII 代表写入文件中。
如果我使用生成 256 个字符串的方法,然后将该字符串写入文件,则该文件的大小为 258 字节。
string fileString = "";
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
fileString += i;
}
file << fileString;
如果我使用循环写入文件的方法,则该文件正好是 256 字节。
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
file << (char)i;
}
字符串发生了什么,字符串中的哪些额外信息被写入文件?
I am using c++ to look through 256 counts and write the ASCII representative to a file.
If i use the method of generating a 256 character string then write that string to the file, the file weighs 258bytes.
string fileString = "";
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
fileString += i;
}
file << fileString;
If i use the method of writing to the file withing the loop, the file is exactly 256bytes.
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
file << (char)i;
}
Whats going here with the string, what extra information from the string is being written to the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这两者都会创建一个 256 字节的文件:
并且:
注意,在出现差一错误之前,因为没有第 256 个 ASCII 字符,只有 0-255。打印时它将截断为字符。另外,更喜欢
static_cast
。如果您不将它们作为二进制文件打开,它将在末尾附加一个换行符。我的标准在输出领域很弱,但我确实知道文本文件应该总是在末尾有一个换行符,并且它正在为您插入这个换行符。我认为这是实现定义的,因为到目前为止我在标准中所能找到的只是“析构函数可以执行其他实现定义的操作”。
当然,以二进制方式打开会删除所有栏,让您控制文件的每个细节。
关于 Alterlife 的问题,您可以在字符串中存储 0,但 C 风格的字符串以 0 结尾。因此:
将打印两种不同的长度:一种被计数,一种以 null 终止。
Both of these create a 256 byte file:
And:
Note, before you had an off-by-one error, as there is no 256th ASCII character, only 0-255. It will truncate to a char when printed. Also, prefer
static_cast
.If you do not open them as binary, it will append a newline to the end. My standard-ess is weak in the field of outputs, but I do know text files are suppose to always have a newline at the end, and it is inserting this for you. I think this is implementation defined, as so far all I can find in the standard is that "the destructor can perform additional implementation-defined operations."
Opening as binary, of course, removes all bars and let's you control every detail of the file.
Concerning Alterlife's concern, you can store 0 in a string, but C-style strings are terminated by 0. Hence:
Will print two different lengths: one that is counted, one that is null-terminated.
我对 C++ 不太熟悉,但是你尝试过用 null 或 '/0' 初始化 filestring 变量吗?也许它会给出 256 字节文件..
N yea 循环应该 < 256
PS:我真的不确定,但我想它值得尝试..
im not too gud with c++ but did you try initializing the filestring variable with null or '/0' ?? Maybe then it will give 256byte file..
N yea loop should be < 256
PS: im really not sure but then i guess its worth trying..