Linux写整数 结构体数组到文件 打破思维定式

一 写入一个整数到文件

在之前我们学习write函数和read函数时

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

上面两个buf缓冲区,我们常常用来写字符或者字符串。通常会认为只能写字符或者字符串。可以看出buf是个指针类型,我们可以传任何地址。它对类型没有要求
我们写入一个整数到文件

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
   int *p;//设置写入缓冲区(int类型指针)
   int *m;//设置读出缓冲区(char类型指针)
   p=(int*)malloc(sizeof(int)*4);//开辟写入缓冲区空间
   m=(int*)malloc(sizeof(int)*4);//开辟读出缓冲区空间
   *p = 100;//给p赋值
   int fd=open("./test2",O_RDWR|O_CREAT,0600);
   write(fd,p,3);//写入函数
   lseek(fd,0,SEEK_SET);
   read(fd,m,3);
   printf("%d",*m);
   close(fd);
}

结果如下:
在这里插入图片描述

二 写入一个结构体到文件

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

struct test{
  int  data;
  char str;
}; //创建一个结构体

int main()
{
   struct test new1 = {100,'a'}; //初始化结构体
   struct test new2;
   int fd=open("./test3",O_RDWR|O_CREAT,0600);
   write(fd,&new1,sizeof(struct test)*1);//写入结构体,传入结构体地址
   lseek(fd,0,SEEK_SET);
   read(fd,&new2,sizeof(struct test)*1);//读到缓冲区
   printf("%d %c",new2.data,new2.str);
   close(fd);
}

三 写入一个结构体数组到文件

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

struct test{
  int  data;
  char str;
};

int main()
{
   struct test data0[3] = {{100,'a'},{200,'b'},{300,'c'}};//定义一个结构体数组
   struct test data2[3];//读入缓冲区
   int fd=open("./test3",O_RDWR|O_CREAT,0600);
   write(fd,&data0,sizeof(struct test)*3);
   lseek(fd,0,SEEK_SET);
   read(fd,&data2,sizeof(struct test)*3);
   printf("%d %c\n",data2[0].data,data2[0].str);
   printf("%d %c\n",data2[1].data,data2[1].str);
   printf("%d %c\n",data2[2].data,data2[2].str);
   close(fd);
}

效果如下:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pg_hj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值