写作结构体在C文件 [英] Writing Structs to a file in c

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

问题描述

是否有可能对整个结构写入一个文件

例如:

 结构日期{
    焦天[80];
    INT月;
    INT年;
};


解决方案

  

是否有可能对整个结构写入一个文件


您的问题是实际编写结构实例到文件中。


  1. 您可以使用 FWRITE 函数来实现这一点。

  2. 您需要传递的第一个参数参考。

  3. 的sizeof 第二个参数中的每个对象

  4. 此类对象的数量在第三个参数写入。

  5. 在第四个参数文件指针。

  6. 请不要忘记二进制模式来打开该文件。

  7. 您可以从文件中使用的fread读取对象。

  8. 小心使用,当你写/读小端系统和读/大端系统,反之亦然写字节顺序。读<一个href=\"http://stackoverflow.com/questions/13994674/how-to-write-endian-agnostic-c-c-$c$c\">how-to-write-endian-agnostic-c-c-$c$c

     结构日期*对象=的malloc(sizeof的(结构日期));
    的strcpy(对象 - &GT;的一天,好天);
    对象 - &GT;当月= 6;
    对象 - &GT;同期= 2013;
    FILE *文件=的fopen(输出,世行);
    如果(文件!= NULL){
        FWRITE(对象的sizeof(结构日期),1,文件);
        FCLOSE(文件);
    }


您可以用同样的方式阅读....使用 FREAD

 结构日期* = Object2的malloc的(sizeof的(结构日期));
    FILE *文件=的fopen(输出,RB);
    如果(文件!= NULL){
        FREAD(Object2的,的sizeof(结构日期),1,文件);
        FCLOSE(文件);
    }
    的printf(%s /%D /%d个\\ N,object2-&GT;的一天,object2-&GT;当月,object2-&GT;一年);

Is it possible to write an entire struct to a file

example:

struct date {
    char day[80];
    int month;
    int year;
};

解决方案

Is it possible to write an entire struct to a file

Your question is actually writing struct instances into file.

  1. You can use fwrite function to achieve this.
  2. You need to pass the reference in first argument.
  3. sizeof each object in the second argument
  4. Number of such objects to write in 3rd argument.
  5. File pointer in 4th argument.
  6. Don't forget to open the file in binary mode.
  7. You can read objects from file using fread.
  8. Careful with endianness when you are writing/reading in little endian systems and reading/writing in big endian systems and viceversa. Read how-to-write-endian-agnostic-c-c-code

    struct date *object=malloc(sizeof(struct date));
    strcpy(object->day,"Good day");
    object->month=6;
    object->year=2013;
    FILE * file= fopen("output", "wb");
    if (file != NULL) {
        fwrite(object, sizeof(struct date), 1, file);
        fclose(file);
    }
    

You can read them in the same way....using fread

    struct date *object2=malloc(sizeof(struct date));
    FILE * file= fopen("output", "rb");
    if (file != NULL) {
        fread(object2, sizeof(struct date), 1, file);
        fclose(file);
    }
    printf("%s/%d/%d\n",object2->day,object2->month,object2->year);

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

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