Linux文件编程之写入一个结构体

前言

        之前我们的只能写入都是char型的字符串,现在我们要想把整形或者结构体写进文件要怎么实现呢?

一、实现思路

 ssize_t write(int fd, const void *buf, size_t count);

        先观察write函数的原型链,第一个参数是目标文件标识符,第二个是一个无参数类型的指针,第三是写入大小。 

        我们要想把整型写入文件,把整型数的地址传进第二个参数即可。

二、整数写入

代码实现:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char  **argv)
{
        int fdSrc;
        int data1=199;
        int data2=0;

        fdSrc=open("./file1",O_RDWR);//打开file1文件


        write(fdSrc,&data1,sizeof(int));//将data1的值写入
        lseek(fdSrc,0,SEEK_SET);//重置光标
        read(fdSrc,&data2,sizeof(int));//将file1内容读到data2里面

        printf("data=%d\n",data2);//输出data2
        close(fdSrc);

        return 0;
}

 成功读取写入值199。

三、一个结构体写入

#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>


struct Test{

        int a;
        char b;
};

int main(int argc,char  **argv)
{
        int fdSrc;
        struct Test data1={199,'a'};
        struct Test data2;

        fdSrc=open("./file1",O_RDWR);


        write(fdSrc,&data1,sizeof(struct Test));
        lseek(fdSrc,0,SEEK_SET);
        read(fdSrc,&data2,sizeof(struct Test));

        printf("int=%d,char=%c\n",data2.a,data2.b);
        close(fdSrc);

        return 0;
}
          

 成功写入一个结构体。

四、写入多个结构体

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
struct Test{

        int a;
        char b;
};

int main(int argc,char  **argv)
{
        int fdSrc;
        struct Test data1[2]={{199,'a'},{200,'b'}};
        struct Test data2[2];

        fdSrc=open("./file1",O_RDWR);


        write(fdSrc,&data1,sizeof(struct Test)*2);
        lseek(fdSrc,0,SEEK_SET);
        read(fdSrc,&data2,sizeof(struct Test)*2);

        printf("int=%d,char=%c\n",data2[0].a,data2[0].b);
        printf("int=%d,char=%c\n",data2[1].a,data2[1].b);

        close(fdSrc);

        return 0;
}
                                                 1,19          Top

 成功写入两个结构体。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值