c++ - 写入二进制文件

标签 c++ binary fstream

#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_cast这到const char*并写入尽可能多的字节来保存 int为您的机器架构。请注意,如果您打算在另一台机器上读取此二进制日期,则必须使用 word size。和 endianness考虑在内。我还建议您将 name 归零和 surname在使用它们之前先缓冲,以免最终在二进制文件中出现未初始化内存的人工制品。

此外,无需将类的属性传递给 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                                     ..

关于c++ - 写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8329767/

相关文章:

c++ - 在继承的情况下不在此范围内声明

javascript - Firefox 扩展中的 Window less embedded exe

python - 通过重复加法进行二进制乘法

c++ - 从 std::fstream 检索文件描述符

c++ - 如何在不安装Windows SDK的情况下在客户端PC上使用编译好的DLL?

c++ - 使用折叠表达式为数组实现 less 运算符

c++ - C++ 中随机位置的二进制输出到文件

C作业,打印出一个整数的二进制值

c++ - 试图读取文本文件 C++

c++ - 使用 pthreads 重新排列数据包