21xrx.com
2024-06-03 01:12:20 Monday
登录
文章检索 我的文章 写文章
C++文件存储技巧
2023-06-29 07:15:13 深夜i     --     --
C++文件读写 文件流 二进制文件存储 序列化 结构体存储

对于C++开发者而言,文件存储是一项常见的工作。无论是读取文件内容,还是将数据写到文件中,都需要掌握一些技巧。下面就为大家介绍几种常用的C++文件存储技巧。

1. 二进制文件存储

二进制文件存储是指将数据以二进制的方式存储到文件中。这种方式的好处是可以大大减少文件的大小,同时还可以提高读取和写入文件的速度。通常,我们需要使用C++的fstream库来进行文件的操作。

例如,在将一个int类型的变量写入二进制文件时,可以使用下面的代码:


#include <fstream>

using namespace std;

int main()

{

  ofstream fout("test.dat", ios::binary); // 创建二进制文件

  int x = 10;

  fout.write((char*)&x, sizeof(int)); // 将变量x以二进制方式写入文件

  fout.close(); // 关闭文件

  return 0;

}

2. 文本文件存储

文本文件存储是指将数据以文本的方式存储到文件中。这种方式的好处是便于读取和编辑,但文件会比较大。和二进制文件类似,我们也需要使用C++的fstream库来进行文件的操作。

例如,在将一个字符串写入文本文件时,可以使用下面的代码:


#include <fstream>

using namespace std;

int main()

{

  ofstream fout("test.txt"); // 创建文本文件

  string str = "Hello, world!";

  fout << str << endl; // 将字符串写入文件

  fout.close(); // 关闭文件

  return 0;

}

3. XML文件存储

XML文件存储是指将数据以XML格式存储到文件中。XML是一种标记语言,它可以让我们更好地组织和存储数据,并便于程序之间进行数据交换。在C++中,我们可以使用一些XML库,如tinyxml, pugixml等来进行XML文件的读写操作。

例如,假设我们有一个学生类,我们可以将它以XML格式写入文件中:


#include <iostream>

#include "pugixml.hpp"

using namespace std;

class Student

{

public:

  string name;

  int age;

  double score;

  void output()

  

    cout << "name: " << name << endl;

    cout << "age: " << age << endl;

    cout << "score: " << score << endl;

  

  void saveXML(pugi::xml_node& node)

  {

    node.append_child("name").text() = name.c_str();

    node.append_child("age").text() = to_string(age).c_str();

    node.append_child("score").text() = to_string(score).c_str();

  }

  void loadXML(pugi::xml_node& node)

  {

    name = node.child_value("name");

    age = atoi(node.child_value("age"));

    score = atof(node.child_value("score"));

  }

};

int main()

{

  Student s;

  s.name = "张三";

  s.age = 20;

  s.score = 90.5;

  pugi::xml_document doc;

  doc.append_child("student");

  s.saveXML(doc.child("student"));

  doc.save_file("test.xml"); // 将XML文件保存到磁盘

  // 从XML文件中读取学生信息

  pugi::xml_parse_result result = doc.load_file("test.xml");

  s.loadXML(doc.child("student"));

  s.output();

  return 0;

}

以上就是C++文件存储的几种常用技巧。它们各自有着自己的特点和用途,开发者需要结合具体情况选择合适的方式。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复