简体   繁体   中英

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

I'm learning file handling in c++ from internet alone. 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*? And how does it read and write the file?

The function fstream::read has the following function signature:

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. 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/

The usage of the char * cast with read and write is to treat the obj variable as generic, continuous, characters (ignoring any structure).

The read function will read from the stream directly into the obj variable, without any byte translation or mapping to data members (fields). 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. 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; no processing of the "end of line" or "end of file" characters. Basically mirror image data transfers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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