溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C/C++中二進制文件和順序讀寫有什么用

發(fā)布時間:2021-09-03 09:29:35 來源:億速云 閱讀:153 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹C/C++中二進制文件和順序讀寫有什么用,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

概述

二進制文件不同于文本文件, 它可以用于任何類型的文件 (包括文本文件).

C/C++中二進制文件和順序讀寫有什么用

二進制 vs ASCII

對于數(shù)值數(shù)據(jù), ASCII 形式與二進制形式不同. ASCII 文件直觀, 便于閱讀, 但一般占存儲空間較多, 而且需要花時間轉(zhuǎn)換. 二進制文件是計算機的內(nèi)部形式, 節(jié)省空間且不需要轉(zhuǎn)換, 但不能直觀顯示.

對于字符信息, 在內(nèi)存中是以 ASCII 代碼形式存放, 無論用 ASCII 文件輸出還是用二進制文件輸出, 形式是一樣的.

二進制寫入

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    int x = 12345;
    ofstream outfile("binary.txt", ios::binary);

    outfile.write((char*)&x, 2);  // 寫入
    outfile.close();  // 釋放

    return 0;
}

輸出結(jié)果:

C/C++中二進制文件和順序讀寫有什么用

ASCII 寫入

將 int x = 12345 寫入文件.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    int x = 12345;
    ofstream outfile("ASCII.txt");
    
    outfile << x << endl;  // 寫入
    outfile.close();  // 釋放

    return 0;
}

輸出結(jié)果:

C/C++中二進制文件和順序讀寫有什么用

read 和 write 讀寫二進制文件

打開方式:

ofstream a("file1.dat", ios::out | ios::binary);
ifstream b("file2.dat",ios::in | ios::binary);

文件讀寫方式:

istream& read(char *buffer,int len);
ostream& write(const char * buffer,int len);
  • char *buffer 指向內(nèi)存中一段存儲空間

  • int len 是讀寫的字節(jié)數(shù)

例子:

將 p1 指向的空間中 50 個字節(jié)存入文件對象 a:

a.write(p1,50)

從文件對象 b 讀出 30 個字節(jié), 存址指向空間:

b.read(p2,30)

案例一

將數(shù)據(jù)以二進制的形式存放在磁盤中.

#include <fstream>
#include <iostream>
#include "Student.h"
using namespace std;

int main() {
    Student stud[2] = {
            {01, "Little White"},
            {01, "Big White"}
    };

    ofstream outfile("student.dat", ios::binary);
    if(!outfile){
        cerr << "open error"  << endl;
        exit(1);  // 退出程序
    }
    for (int i = 0; i < 2; ++i) {
        outfile.write((char*)&stud[i], sizeof(stud[i]));
    }
    cout << "任務完成, 請查看文件" << endl;
    outfile.close();

    return 0;
}

案例二

將二進制文件中的數(shù)據(jù)讀入內(nèi)存.

#include <fstream>
#include <iostream>
#include "Student.h"
using namespace std;

int main() {
    Student stud[2];

    ifstream infile("student.dat", ios::binary);
    if(!infile){
        cerr << "open error"  << endl;
        exit(1);  // 退出程序
    }

    // 讀取數(shù)據(jù)
    for (int i = 0; i < 2; ++i) {
        infile.read((char*)&stud[i], sizeof(stud[i]));
    }
    infile.close();

    // 顯示數(shù)據(jù)
    for (int i = 0; i < 2; ++i) {
        stud[i].display();
    }

    return 0;
}

以上是“C/C++中二進制文件和順序讀寫有什么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI