c++ - iostream::write() 中需要 sizeof() 吗?

标签 c++ sizeof ostream

我认为标准库可以在这样的代码中调用模板类型的 sizeof 运算符(不是吗?):

#include <fstream>

int main()
{
    std::ofstream file("test.bin", std::ios::binary | std::ios::out);
    char buf = 42;

    file.write(&buf, sizeof(buf));
}

那么是否有理由向程序员询问要在 ostream::write() 中写入的元素的大小?

PS:这是我的第一个问题,我不是英语,放纵一下

最佳答案

char * 可能是

char const c = 'a';
char const * ptr = &c;        // char const *

如您的示例,但它也可以是字符串文字

std::string x("some string");
char const * ptr = x.c_str(); // also char const *!!

当您只有指针可用时,您如何决定要读取的内存地址?你需要一个长度:

file.write(x.c_str(), x.length());

关于c++ - iostream::write() 中需要 sizeof() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18237890/

相关文章:

c++推导 "non type pointer to function"类模板参数

c++ - 来自不同命名空间的 friend 方法

c - 什么是 sizeof() 检查作为 C 中 int array[] 的标记值

c++ - sizeof ('ab' ) 是否等于 C++ 中的 sizeof(int)?

c++ - 如何在数组中的对象上调用 << 运算符?

c++ directshow filter 私有(private)接口(interface)

c++ - 如何同步EXE/DLL文件的SVN版本和版本资源?

C 中数组大小的混淆

c++ - setw 在一个函数中返回一个 ostream

c++ - ostream:在 cout 或文件上输出的类