c - 从文件中读取结构内的结构

标签 c structure

下面是定义的结构。

typedef struct{
    int a;
    char b;
}X;
typedef struct{
    X m;
    int c;
    char d;
}B;
B n,q;
n.m.a = 12;
n.m.b = 'a';
n.c = 13;
n.d = 'b';

我在文件中写入以下结构。文件打开如下。

fp = fopen("D://tests//t11test.txt","wb");
fwrite(&n, sizeof(B), 1, fp);

fwrite成功,查看了fp对应的文件内容。 但是,当我在关闭并重新打开文件后对同一文件执行 fread 时,我无法读取子结构 m 的内容。最可怕的是

fp = fopen("D://tests//t11test.txt","rb");
fread(&q, sizeof(B), 1,fp);

我哪里出错了?

最佳答案

我看不出问题是什么,但是,FWIW,这有效:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>

typedef struct{ int a; char b; }X;
typedef struct{ X m; int c; char d; }B;

void print_B(B* a_b)
{
    printf("{ { %d, %c }, %d, %c }",
           a_b->m.a,
           a_b->m.b,
           a_b->c,
           a_b->d);
}

int main()
{
    /* Write structure. */
    {
        FILE* fp;
        B n;
        n.m.a = 12;
        n.m.b = 'a';
        n.c = 13;
        n.d = 'b';
        fp = fopen("x.dat", "wb");
        assert(0 != fp);
        if (1 != fwrite(&n, sizeof(B), 1, fp))
        {
            fprintf(stderr, "Failed to fwrite(): %s\n", strerror(errno));
            return 1;
        }
        fclose(fp);

        printf("wrote: ");
        print_B(&n);
        printf("\n");
    }

    /* Read structure. */
    {
        FILE* fp;
        B q;
        fp = fopen("x.dat", "rb");
        assert(0 != fp);
        if (1 != fread(&q, sizeof(B), 1, fp))
        {
            fprintf(stderr, "Failed to fread(): %s\n", strerror(errno));
            return 1;
        }
        fclose(fp);

        printf("read : ");
        print_B(&q);
        printf("\n");
    }

    return 0;
}

输出:

wrote: { { 12, a }, 13, b }
read : { { 12, a }, 13, b }

关于c - 从文件中读取结构内的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9699406/

相关文章:

c# - 在不使用不安全的情况下将 int 分配给结构对象

c++ - 错误与 'operator=' 不匹配(操作数类型为 'Person' 和 'Person*' )

c - C 中的文件、访问指针、读取和写入文件

c - 如果前一个数组是同一位置的字符,则填充数组

c - 以下错误消息 "error: invalid operands to binary expression (' double' 和 'double' )” 是什么意思?

将无符号字符转换为有符号整数

c - 对于结构变量s1,s2,为什么我可以初始化 "s1={25,3.5}",将s2赋值为 "s1=s2",然后就不能使用“s1={59,3.14}?

logic - LabVIEW中的未知图标

c - 函数未正确返回 char : error during compile

c - 使用未命名管道编写我自己的 Linux shell