是否定义了默认的ofstream实现模式? [英] Is the default mode of ofstream implementation defined?

查看:235
本文介绍了是否定义了默认的ofstream实现模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

std::ofstream stream("somefile");

if (!stream)
{
   return 1;
}

调用 .write(....)并使用 stdc ++ libc ++ 时,流处于二进制模式(std::ios::binary) .

When invoking .write(....) and using stdc++ and libc++ the stream is in binary mode (std::ios::binary).

但是,当使用 MSVC (2015/2017RC1)时,它似乎处于文本模式或某种奇怪的状态,因为生成的文件大于实际写入的文件.

However when using MSVC (2015/2017RC1) it seems to be in text mode or something weird, because the the resulting file is larger than what is actually written.

但是,如果我明确设置了模式std::ios::binary,则MSVC的行为类似于之前提到的其他标准库的std::ofstream实现.

But if i explicitly set the mode std::ios::binary MSVC behaves similarly to the std::ofstream implementations of other standard libraries mentioned earlier.

示例代码:

#include <vector>
#include <cstdio>
#include <fstream>

std::size_t fsz(const char* filename) {
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return static_cast<std::size_t>(in.tellg());
}

int main() {
   std::ofstream stream("filename");

   if (!stream)
      return 1;

   std::vector<unsigned long long int> v = {0x6F1DA2C6AC0E0EA6, 0x42928C47B18C31A2, 0x95E20A7699DC156A, 0x19F9C94F27FFDBD0};

   stream.write(reinterpret_cast<const char*>(v.data()),v.size() * sizeof(unsigned long long int));

   stream.close();

   printf("expect: %d\n", v.size() * sizeof(unsigned long long int));
   printf("file size: %d\n", fsz("filename"));

   return 0;
}

使用msvc运行时,上述代码的输出:

Output for the above code when run with msvc:

expect: 32 
file size: 33

与libc ++,stdc ++一起运行时,上述代码的输出:

Output for the above code when run with libc++, stdc++:

expect: 32 
file size: 32

差异会变得更大,这取决于写入的数据量和数据的内容.

The difference can get much larger, it depends on how much data is written and the contents of the data.

最后我的问题还是一样,是未定义还是未指定的行为?

at the end my question is still the same, is it undefined or unspecified behavior?

将上述向量更改为以下内容,可以使示例在发生情况时更加明显.

changing the above vector to the following makes the example more obvious as to whats going on.

std::vector<unsigned long long int> v = {0x0A0A0A0A0A0A0A0A, 0x0A0A0A0A0A0A0A0A, 0x0A0A0A0A0A0A0A0A, 0x0A0A0A0A0A0A0A0A};

推荐答案

流构造函数使用的默认模式为ios_base::out.由于没有显式的text模式标志,这意味着该流以文本模式打开.文本模式仅在Windows系统上起作用,它将\n字符转换为CR/LF对.在POSIX系统上,它无效,并且文本和二进制模式在这些系统上是同义词.

The default mode used by the stream constructor is ios_base::out. As there is no explicit text mode flag, this implies the stream is opened in text mode. Text mode only has an effect on Windows systems, where it converts \n characters to CR/LF pairs. On POSIX systems it has no effect, and text and binary modes are synonymous on these systems.

这篇关于是否定义了默认的ofstream实现模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆