如何将结构读取/写入文件 [英] How to read/write a stucture to a file

查看:68
本文介绍了如何将结构读取/写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct DATA
{
    int num;
    string str;
};



我不知道如何从文本文件中读取(也许也可以写入)此结构,因为有一个字符串!
我这样写:



I don''t know how to read (maybe also write)this structure from a text file because there is a string!
I wrote like these:

WriteFile(hFile, &data, sizeof(data)…


并阅读


and read

DATA data;
ReadFile(hFile, &data, sizeof(DATA)…



但是,每次运行程序时,都会出现_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)错误.也许是因为我没有为str分配内存,实际上我不知道该怎么做.
我知道如果我使用char str[STRING_LENGTH]可以正常工作,但是字符串的长度不是恒定的.

那么我该如何处理呢?还是有其他方法可以完成相同的工作?



But, everytime I run the program, I got a _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) error. Maybe this is because I didn''t allocated memory for the str, actually I don''t know how to do it.
I know it works if I use char str[STRING_LENGTH] but the length of the string isn''t constant.

So how should I deal with it? Or is there other way to do the same work?

推荐答案

您需要序列化和反序列化才能向文件写入和读取结构或类.它始终是首选方法:)
因此,请查看以下文章 [
You need serialization and deserialization to write and read structures or class to a file. It is always a preferred method :)
so have a look with the below article [^]


这篇关于如何将结构读取/写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆