簡體   English   中英

寫入二進制文件

[英]writing into binary files

#include <iostream>
#include <fstream>

using namespace std;

class info {

private:
    char name[15];
    char surname[15];
    int age;
public:
    void input(){
        cout<<"Your name:"<<endl;
            cin.getline(name,15);
        cout<<"Your surname:"<<endl;
        cin.getline(surname,15);
        cout<<"Your age:"<<endl;
        cin>>age;
        to_file(name,surname,age);
    }

    void to_file(char name[15], char surname[15], int age){
        fstream File ("example.bin", ios::out  | ios::binary | ios::app);
    // I doesn't know how to fill all variables(name,surname,age) in 1 variable (memblock) 
        //example File.write ( memory_block, size ); 

File.close();
    }

};

int main(){

info ob;
ob.input();

 return 0;
}

我不知道如何將1個以上的變量寫入文件,請幫助,我包含了一個例子;)也許有更好的方法來寫一個文件,請幫我這個,這對我來說很難解決。

對於文本文件,您可以使用類似<<到與std::cout一起使用的<<

對於二進制文件,您需要使用std::ostream::write() ,它寫入一個字節序列。 對於你的age屬性,你需要將它reinterpret_castconst char*並寫入為你的機器架構保存int所需的字節數。 請注意,如果您打算在另一台計算機上讀取此二進制日期,則必須考慮字大小字節順序 我還建議您在使用namesurname緩沖區之前將其歸零,以免最終在二進制文件中出現未初始化內存的偽影。

此外,不需要將類的屬性傳遞給to_file()方法。

#include <cstring>
#include <fstream>
#include <iostream>

class info
{
private:
    char name[15];
    char surname[15];
    int age;

public:
    info()
        :name()
        ,surname()
        ,age(0)
    {
        memset(name, 0, sizeof name);
        memset(surname, 0, sizeof surname);
    }

    void input()
    {
        std::cout << "Your name:" << std::endl;
        std::cin.getline(name, 15);

        std::cout << "Your surname:" << std::endl;
        std::cin.getline(surname, 15);

        std::cout << "Your age:" << std::endl;
        std::cin >> age;

        to_file();
    }

    void to_file()
    {
        std::ofstream fs("example.bin", std::ios::out | std::ios::binary | std::ios::app);
        fs.write(name, sizeof name);
        fs.write(surname, sizeof surname);
        fs.write(reinterpret_cast<const char*>(&age), sizeof age);
        fs.close();
    }
};

int main()
{
    info ob;
    ob.input();
}

示例數據文件可能如下所示:

% xxd example.bin
0000000: 7573 6572 0000 0000 0000 0000 0000 0031  user...........1
0000010: 3036 3938 3734 0000 0000 0000 0000 2f00  069874......../.
0000020: 0000                                     ..
File.write(name, 15);
File.write(surname, 15);
File.write((char *) &age, sizeof(age));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM