C++将字符串写入文件=额外字节

Sha*_*ean 1 c++ string file filesize

我使用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;
Run Code Online (Sandbox Code Playgroud)

如果我使用循环写入文件的方法,文件正好是256字节.

//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
    file << (char)i;
}
Run Code Online (Sandbox Code Playgroud)

什么是字符串,字符串中的哪些额外信息被写入文件?

GMa*_*ckG 6

这两个都创建一个256字节的文件:

#include <fstream>
#include <string>

int main(void)
{
    std::ofstream file("output.txt", std::ios_base::binary);
    std::string fileString;

    for(int i = 0; i < 256; i++)
    {
        fileString += static_cast<char>(i);
    }

    file << fileString;
}
Run Code Online (Sandbox Code Playgroud)

和:

#include <fstream>
#include <string>

int main(void)
{
    std::ofstream file("output.txt", std::ios_base::binary);
    std::string fileString;

    for (int i = 0; i < 256; ++i)
    {
        file << static_cast<char>(i);
    }

    file.close();
}
Run Code Online (Sandbox Code Playgroud)

注意,在你有一个一个一个错误之前,因为没有第256个ASCII字符,只有0-255.它会在打印时截断为char.另外,更喜欢static_cast.

如果不以二进制形式打开它们,它会在末尾添加换行符.我的标准ess在输出领域很弱,但我知道文本文件最终总是有一个换行符,并且它会为你插入.我认为这是实现定义的,因为到目前为止,我在标准中找到的是"析构函数可以执行其他实现定义的操作".

当然,打开二进制文件会删除所有条形图,让您控制文件的每个细节.


关于Alterlife的问题,您可以在字符串中存储0,但C样式的字符串以0结尾.因此:

#include <cstring>
#include <iostream>
#include <string>

int main(void)
{
    std::string result;

    result = "apple";
    result += static_cast<char>(0);
    result += "pear";

    std::cout << result.size() << " vs "
        << std::strlen(result.c_str()) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

将打印两种不同的长度:一种是计数的,一种是以空值终止的.