Read and Write files in binary mode in C ++

Source: Internet
Author: User

Today, I learned how to use C ++ to store binary files. I have been discussing it with seven for a long time on QQ and haven't made it yet. Later I found it a function problem.

It is estimated that many people know how to use it.

 
Ofstream out ("test. Binary", IOS: Binary | IOs: Out );

And this

 
Ifstream in ("test. Binary", IOS: Binary | IOs: In );

These two methods are used to set File Reading and Writing. They are in binary format. However, it is very important that you cannot directly use out <and in>, read and Write Functions are required. The following is a simple example.

# Include <iostream> # include <string> # include <fstream> using namespace STD; void save () {ofstream out ("test. binary ", IOS: Binary | IOs: Out); short B =-189; out. write (const char *) & B, sizeof (B); float a; For (INT I = 0; I <10; I ++) {A = 0.128937; out. write (const char *) & A, sizeof (a);} Out. close (); out. clear ();} void load () {ifstream in ("test. binary ", IOS: Binary | IOs: In); short U1; In. read (char *) & u1, sizeof (U1); cout <U1 <Endl; For (INT I = 0; I <10; I ++) {float AA; In. read (char *) & aa, sizeof (AA); cout <AA <Endl;} In. close (); In. clear () ;}int main () {int upset; save (); load (); CIN >>upset; return 0 ;}

It is certainly no problem to store the data in this way, and there is no problem to read the data. after a busy day, it is actually so simple. I am also eager to consider what byte array and what type conversion to use, it's speechless.

Okay, don't ask seven any more.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.