當前位置:編程學習大全網 - 網站源碼 - c++包含string類的結構體類型二進制文件讀入輸出

c++包含string類的結構體類型二進制文件讀入輸出

// 不知道妳的 KeyType 是什麽類型就把他省掉了。

// 如果用C的話記得把輸出語句改成printf;

#include <stdio.h>

#include <string>

#include <iostream>

using namespace std;

struct ElemType{

string content; //內容域

int num;

};

// 無論妳結構體裏有哪些數據,都可以用下面的代碼。

int main(void)

{

struct ElemType sNode;

sNode.num = 100;

sNode.content = "hello world!";

// 寫入文件

FILE *pFile = fopen("1.txt", "wb"); // 用二進制打開

int size = sizeof(sNode);

fwrite(&size, sizeof(int), 1, pFile);

fwrite(&sNode, sizeof(sNode), 1, pFile);

fclose(pFile);

// 讀取文件

struct ElemType sRnode;

FILE *pRfile = fopen("1.txt", "rb");

fread(&size, sizeof(int), 1, pRfile);

fread(&sRnode, size, 1, pRfile);

fclose(pRfile);

cout << sRnode.content << endl;

cout << sRnode.num << endl;

}

  • 上一篇:Chibo源代碼
  • 下一篇:完全不懂金融,想學習量化投資需要學習哪些金融科目
  • copyright 2024編程學習大全網