Linux文件操作——其他类型数据写到文件并读取

函数原型

由前面章节可知,对文件的操作都是基于字符串,但对文件的操作并不仅限于此,这个时候需要重新审视几个文件操作的函数原型,函数原型如下:

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

其中无论是写入(write)还是读取(read)函数,其第二个参数都是无类型的指针,而指针就是地址,前面我们是直接写入字符串名字,因为字符串名字就是地址,所以第二个参数我们只需要写入相应数据类型的地址即可。那么我们可以写入一个整型变量并读取,也可以写入一个结构体并读取,甚至写入一个结构体数组并读取。

写入整型变量并读取

写入整型变量时我们将函数的第二个参数写入整型变量名并取地址,在计算字节时只需计算整型变量的字节数即可。

代码展示

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
 
int main()
{
    nt fd;
	int data1 = 100;
	int data2 = 0;
 
	fd = open("./file1",O_RDWR);
 
    int n_write = write(fd,&data1,sizeof(int));//将data1取地址,由于data1是整型数,其大小就是int的字节数(系统为4个字节),将其写入文件描述符fd对应的文件file1
 
	lseek(fd,0,SEEK_SET);//将光标移到文件头,方便读取
 
	int n_read = read(fd,&data2,sizeof(int));//与写入函数类似
    printf("data2 is %d\n",data2);
 
    return 0;
}
 
                     

 可见data2原先值为0,但通过编译后,data2的值为100,实现了写入整型变量并读取

不过在写入的file1文件内的数据为乱码是由于在Linux底下的编码不同,故会显示乱码。不过经程序编译是正确的,就可以了。

写入结构体并读取

写入结构体时我们需定义一个结构体,将第二个参数写入结构体地址,同时字节计算时只需计算结构体大小即可

代码

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
 
struct Test
{
	int a;
	char b;
};
 
int main()
{
    int fd;
	struct Test data1 = {114,'w'};
	struct Test data2;
 
	fd = open("./file1",O_RDWR|O_TRUNC);
 
    int n_write = write(fd,&data1,sizeof(struct Test));
 
	lseek(fd,0,SEEK_SET);
 
	int n_read = read(fd,&data2,sizeof(struct Test));
    printf("data2 is %d,%c\n",data2.a,data2.b);
 
    return 0;
}
 
                     

可见一开始结构体data2中没有数据,通过调用两个函数后将结构体data1的值赋给结构体data2,实现了写入结构体并读取

然而在file文件中还是乱码

写入结构体数组并读取

写入结构体数组与结构体类似,只需在结构体前加数组符号即可

代码

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
 
struct Test
{
	int a;
	char b;
};
 
int main()
{
    int fd;
	struct Test data1[2] ={ {114,'w'},{514,'x'}};
	struct Test data2[2];
 
	fd = open("./file1",O_RDWR);
 
    int n_write = write(fd,&data1,sizeof(struct Test)*2);
 
	lseek(fd,0,SEEK_SET);
 
	int n_read = read(fd,&data2,sizeof(struct Test)*2);
    printf("data2 is %d,%c\n",data2[0].a,data2[0].b);//需用数组下标指向结构体数据
	printf("data2 is %d.%c\n",data2[1].a,data2[1].b);
 
    return 0;
}

甚至还能写入链表

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值