简体   繁体   English

将结构变量写入 c++ 中的文件

[英]Writing structure variables to file in c++

I am trying to store a structure variable in a file in visual c++.我正在尝试将结构变量存储在可视 c++ 的文件中。 Here is my code-这是我的代码-

#include<iostream>
#include<fstream>

using namespace std;

struct node {
    int key;
};

int main() {
    node n1, n2;
    n1.key = 39;
    ofstream fout("data.txt", ios::out);
    //fout.seekp(0);
    fout.write(reinterpret_cast<char*>(&n1), sizeof(node));
    std::cout << "position of put pointer after write: " << fout.tellp() << '\n';
    //fin.seekg(-1);
    ifstream fin("data.txt", ios::in);
    fin.read(reinterpret_cast<char*>(&n2), sizeof(node));
    std::cout << "Key: " << n2.key;
    return 0;
}

When reading the structure back, the value in the key field is a junk value.回读结构时,键字段中的值是垃圾值。 Is there something I am doing wrong?有什么我做错了吗?

Close fout before you open fin.在打开鳍之前关闭 fout。 This works.这行得通。

#include<iostream>
#include<fstream>

using namespace std;

struct node {
    int key;
};

int main() {
    node n1, n2;
    n1.key = 39;
    ofstream fout("data.txt", ios::out);
    //fout.seekp(0);
    fout.write(reinterpret_cast<char*>(&n1.key), sizeof(node));
    std::cout << "position of put pointer after write: " << fout.tellp() << '\n';
    fout.close();
    //fin.seekg(-1);
    ifstream fin("data.txt", ios::in);
    fin.read(reinterpret_cast<char*>(&n2.key), sizeof(node));
    std::cout << "Key: " << n2.key;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM