读取和写入文件的结构 [英] Read and Write a struct to a file

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

问题描述

您好。

如果我有结构:



Hello.
If I have a structure:

struct user {
    char* username;
    char* password;
    int ID;
}





我创建了一个这样的对象:



And I create an object like this:

user user1;

这里对象user1的内存大小为POINTER + POINTER + INT?



但是如果我想将用户扩展为:

Here the object user1 has the size in memory of POINTER + POINTER + INT ?

But if I want to expand the user to:

user1.username = "Hellen";



这里发生了什么?对象在指针后展开并添加数据?或者结构中的指针本身也有INT的空间?



我想从文件中读取数据,我不知道如何继续。



阅读结构以8个字符开头或以指针开头?我需要知道要读取多少数据。


What happens here ? The object expands and add data after the pointer? Or the pointer itself in the strucure also has the space of the INT ?

I want to read the data from the file and I dont know how to proceed.

Read the struct starting with 8 characters or starting with the pointer ? I need to know how much amount of data to read.

推荐答案

我认为独立于文件的读/写,你需要了解C /中的指针C ++。查看有关指针的任何教程,例如 http://www.cprogramming.com/tutorial/c/lesson6.html [ ^ ]。



因为您使用C ++,我强烈建议不要使用普通的char指针进行字符串处理,而是使用 std :: string 类来处理内存管理。



干杯

Andi
I think independent of read/write from/to a file, you need to understand pointers in C/C++. See any tutorial on pointers, e.g. http://www.cprogramming.com/tutorial/c/lesson6.html[^].

Since you work in C++, I strongly recommend not to use plain char pointers for string handling, but rather the std::string class that takes care of memory management.

Cheers
Andi


user1.username = "Hellen";



这不是更改结构的大小,它只是设置用户名指向字符串Hellen,它存储在某个地方在记忆中。如果您现在将结构写入文件,那么您将丢失所有数据,因为您正在编写的是两个指针和一个整数。您最好使用类而不是结构,并研究序列化以确保您可以在必要时将对象保留在磁盘上。


This does not change the size of the structure, it just sets username to point to the string "Hellen", which is stored somewhere else in memory. If you now write the structure to a file, then you lose all the data, since all you are writing is two pointers and an integer. You would be better to use classes instead of structs, and study serialisation to ensure that you can persist your objects on disk when necessary.


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

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