具有指向文件的指针的读写结构 [英] Write/Read structure with pointers to file

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

问题描述

我必须将结构写入文件,以便以后可以读取.结构为:

I have to write a structure to a file so i can read it in later. The struct is:

struct prog{
    char* title;
    char* channel;
    struct tm* start;
    struct tm* end;
    float review;
    enum soort sort;
    union type *type;
};

union type{
    struct serie *ep;
    struct film *mov;
};

struct serie{
    int seznum;
    int epnum;
    char* eptitle;
};

struct film{
    char* reg;
    char* act;
   char* genre;
};

enum sort { film, serie }

因此,您可以看到存在指向字符串和结构tm的指针(来自time.h).我不知道如何将其写入二进制文件,我所能做的就是逐个字符串地将其写入,但是必须有一种更有效的方式来写入先前的结构.我认为问题始于char *和指向tm结构的指针,因为该程序现在要编写字符串开头的地址或tm结构的地址.我不会将字符串而不是地址写到文件中.我尝试使用记录I/O,但它会写入地址,因此以后无法读取它们.谢谢!

So you can see that there are pointers to strings and the struct tm (from time.h). I can't figure out how to write it to a binary file, all i can do is write it string by string but there must be a more efficient way to write the previous struct. I think the problem starts with the char* and the pointers to the tm structs because the program is now going to write the adress of the start of a string or the adress of the tm struct. I wan't to write the string and not the adress to a file. I tried with record I/O but it writes the adresses so i can't read them later. Thanks!

推荐答案

您可能想看看time_t或其他可以将时间存储在单个整数时间戳中的替代方法.您还可以使用数据库或简单的文件存储类.

You may want to look at time_t or other alternatives which can store time in a single integer timestamp. You can also use a database or a simple file storage class.

否则,您无法使用本机C函数真正改善此问题.您可以删除指针并使用固定字符数组,如下所示:

Otherwise you can't really improve this with native C functions. You could remove pointers and use fixed character arrays like so:

struct T_film
{
   char text[50];
   int  i;
};

struct T_prog
{
   char title[50];
   tm start;
   tm end;
   T_film film;
};

T_prog data;//initialize...
fwrite(&data, 1, sizeof(T_prog), fout);

fseek(fin,0,0);
fread(&data, 1, sizeof(T_prog), fin);

现在,该结构具有固定的模式,所有内容都可以二进制形式存储.但是,这可能会更加低效.文本的大小太短或太长,带有多余的空白,这需要花费很长的时间才能阅读.它也不是便携式的.因此,您可能要坚持使用临时方法进行指针操作和读取/写入.

Now the structure has a fixed pattern and everything can be stored in binary. BUT, this can be even more inefficient. The size of text is too short, or too long with extra blank space which takes too long to read. It's not portable either. So you may want to stick to pointers and reading/writing with makeshift methods.

您还可以分离固定大小的数据,并将其放在单独的结构中.将固定大小的数据写在一个块中,然后一一写入字符串.

You can also separate fixed sized data and put them in a separate structure. Write the fixed sized data in one block, then write the character strings one by one.

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

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