简体   繁体   English

C++ 文件处理中的读写函数是如何工作的?

[英]How does read and write function work in C++ file handling?

I'm learning file handling in c++ from internet alone.我正在仅从 Internet 学习 C++ 中的文件处理。 I came across the read and write function.我遇到了读写功能。 But the parameters they take confused me.但是他们采用的参数让我感到困惑。 So, I found the syntax as所以,我发现语法为

fstream fout;
fout.write( (char *) &obj, sizeof(obj) );

and

fstream fin;
fin.read( (char *) &obj, sizeof(obj) );

In both of these, what is the function of char*?在这两个中,char*的作用是什么? And how does it read and write the file?它是如何读写文件的?

The function fstream::read has the following function signature:函数fstream::read具有以下函数签名:

istream& read (char* s, streamsize n);

You need to cast your arguments to the correct type.您需要将参数转换为正确的类型。 (char*) tells the compiler to pretend &obj is the correct type. (char*)告诉编译器假装&obj是正确的类型。 Usually, this is a really bad idea.通常,这是一个非常糟糕的主意。

Instead, you should do it this way:相反,你应该这样做:

// C++ program to demonstrate getline() function 
  
#include <iostream> 
#include <string> 
using namespace std; 
  
int main() 
{ 
    string str; 
  
    fstream fin;
    getline(fin, str); // use cin instead to read from stdin
  
    return 0; 
} 

Source: https://www.geeksforgeeks.org/getline-string-c/来源: https : //www.geeksforgeeks.org/getline-string-c/

The usage of the char * cast with read and write is to treat the obj variable as generic, continuous, characters (ignoring any structure). char * cast 与readwrite的用法是将obj变量视为通用的、连续的、字符(忽略任何结构)。

The read function will read from the stream directly into the obj variable, without any byte translation or mapping to data members (fields). read函数将从流中直接读取到obj变量中,无需任何字节转换或映射到数据成员(字段)。 Note, pointers in classes or structures will be replaced with whatever value comes from the stream (which means the pointer will probably point to an invalid or improper location).请注意,类或结构中的指针将替换为来自流的任何值(这意味着指针可能指向无效或不正确的位置)。 Beware of padding issues.注意填充问题。

The write function will the entire area of memory, occupied by obj , to the stream. write函数会将obj占用的整个内存区域write流。 Any padding between structure or class members will also be written.结构或类成员之间的任何填充也将被写入。 Values of pointers will be written to the stream, not the item that the pointer points to.指针的值将写入流,而不是指针指向的项目。

Note: these functions work "as-is".注意:这些函数“按原样”工作。 There are no conversions or translations of the data.没有数据的转换或翻译。 For example, no conversion between Big Endain and Little Endian;例如,Big Endain 和 Little Endian 之间没有转换; no processing of the "end of line" or "end of file" characters.不处理“行尾”或“文件尾”字符。 Basically mirror image data transfers.基本上是镜像数据传输。

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

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