C语言 在 c 中将结构写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16997141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:37:56  来源:igfitidea点击:

Writing Structs to a file in c

cfile-iostructure

提问by amarVashishth

Is it possible to write an entire struct to a file

是否可以将整个结构写入文件

example:

例子:

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

回答by pinkpanther

Is it possible to write an entire struct to a file

是否可以将整个结构写入文件

Your question is actually writing struct instances into file.

您的问题实际上是将 struct 实例写入文件。

  1. You can use fwritefunction to achieve this.
  2. You need to pass the reference in first argument.
  3. sizeofeach 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);
    }
    
  1. 您可以使用fwrite函数来实现这一点。
  2. 您需要在第一个参数中传递引用。
  3. sizeof第二个参数中的每个对象
  4. 要在第三个参数中写入的此类对象的数量。
  5. 第四个参数中的文件指针。
  6. 不要忘记在binary mode.
  7. 您可以使用 fread 从文件中读取对象。
  8. 在小端系统中写入/读取和在大端系统中读取/写入时要小心字节序,反之亦然。阅读how-to-write-endian-agnostic-cc-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

你可以用同样的方式阅读它们......使用 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);