qq_42010270 2022-02-22 23:47 采纳率: 100%
浏览 284
已结题

c语言write与read函数读取写入结构体到文件问题

将结构体赋值后写入文件,再用read函数读取到结构体指针中,并没有获取到打印信息,请教这是怎么回事!!


#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

struct flow
{
    unsigned int num;
    char name[32];
    unsigned char metric;
};

int main(int argc, const char *argv[])
{
    int fd = open("./open.txt",O_RDWR | O_CREAT | O_TRUNC,0666);
    if(fd == -1)
    {
        perror("open failed");
        return -1;
    }

    struct flow t;
    memset(&t, 0, sizeof(struct flow));
    t.num = 5;
    strcpy(t.name, "test");
    t.metric = 127;
    write(fd, &t, sizeof(struct flow));

       struct flow *p = NULL;
    p = (struct flow*)malloc(sizeof(struct flow)); 

    printf("ret1: %d\n", ret1);

    //读取
    int ret1 = lseek (fd, 0, 0);
    if (read(fd, p, sizeof(struct flow) == -1))
    {
        printf("read error\n");
        exit(1);
    }

    //没有打印信息,貌似没有读取成功
    printf("==> %d\n", p->num);
    printf("==> %s\n", p->name);
    printf("==> %d\n", p->metric);
    close(fd);
    return 0;
}



  • 写回答

2条回答 默认 最新

  • _GX_ 2022-02-23 00:19
    关注
    #include <stdio.h>
    #include <stdlib.h>
    
    struct flow
    {
        unsigned int num;
        char name[32];
        unsigned char metric;
    };
    
    int main(int argc, const char *argv[])
    {
        FILE *file = fopen("open.bin", "w+b");
        if (!file)
        {
            printf("failed to open file\n");
            return -1;
        }
    
        struct flow t = {5, "test", 127};
        fwrite(&t, sizeof(struct flow), 1, file);
    
        struct flow *p = (struct flow *)malloc(sizeof(struct flow));
        rewind(file);
        if (fread(p, sizeof(struct flow), 1, file) != 1)
        {
            printf("read error\n");
            return 1;
        }
        fclose(file);
    
        printf("==> %d\n", p->num);
        printf("==> %s\n", p->name);
        printf("==> %d\n", p->metric);
    
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月3日
  • 已采纳回答 2月23日
  • 创建了问题 2月22日

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站