简体   繁体   English

C++文件处理打开

[英]C++ file handling opening

while (file.read((char *)&vg, sizeof(vg))) what is significance of 'char' over here? while (file.read((char *)&vg, sizeof(vg))) 'char' 在这里的意义是什么? I do not know the why do we use 'char' while reading text from 'dat' file in c++ programming.我不知道为什么我们在 C++ 编程中从“dat”文件中读取文本时使用“char”。

I try to answer this even w/oa MCVE , assuming that file is a std::istream (including a class derived from that).我什至尝试在没有MCVE 的情况下回答这个问题,假设该filestd::istream (包括从中派生的类)。

The member std::istream::read(char_type*, std::streamsize) takes as first argument a std::istream::char_type* = char* .成员std::istream::read(char_type*, std::streamsize)std::istream::char_type* = char*作为第一个参数。 The C-style syntax C 风格的语法

(char*)(ptr)

casts ptr to a pointer to char .ptr转换为指向char的指针。 In this case, the address of vg is reinterpreted as the address to an array of char .在这种情况下, vg的地址被重新解释为char数组的地址。 This cast is necessary so that read() can be called.此强制转换是必需的,以便可以调用read() A char is used here to hold a byte: the code reads from file and writes the object vg byte by byte.这里使用一个char来保存一个字节:代码从文件中读取并逐字节写入对象vg

Assuming file is a std::fstream , that function read expects a char* , which means "a buffer of bytes into which I can read the value of the bytes from the file".假设filestd::fstream该函数read需要一个char* ,这意味着“我可以从文件中读取字节值的字节缓冲区”。

You didn't show a proper testcase, but we must assume that vg is not a buffer of bytes, but actually some object (like, perhaps, an integer).您没有展示正确的测试用例,但我们必须假设vg不是字节缓冲区,而是实际上是某个对象(例如,可能是整数)。 By casting a VgsType* to char* , you allow the read function to continue as if it were operating on the underlying bytes that make up vg .通过将VgsType*强制转换为char* ,您可以让read函数继续运行,就好像它在对构成vg的底层字节进行操作一样。

Note that sometimes this is logically unsafe;请注意,有时这在逻辑上是不安全的; it depends on what vg is.这取决于vg是什么。 However, the actual cast to char* is valid because the standard specifically permits it as a way to inspect the byte representation of an object.但是,实际转换为char*是有效的,因为标准特别允许将其作为检查对象字节表示的一种方式。

The following syntax (char*) it's a C style cast to char* .以下语法(char*)是转换为char*的 C 风格。 So it's taking the address of vg by doing &vg and converting it to a char* .所以它通过执行&vg并将其转换为char*来获取 vg 的地址。 The read function must need an argument of type char* or a type that can be implicitly convertible to char* . read 函数必须需要一个char*类型的参数或一个可以隐式转换为char*

It is generally better to use static_cast instead.通常最好使用static_cast代替。 Also I would try to read from file without needing to cast as general practice(as not all types can be casted to other types), that should be possible using the standard library streams.此外,我会尝试从文件中读取,而无需将其转换为一般做法(因为并非所有类型都可以转换为其他类型),这应该可以使用标准库流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM