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

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日

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助