我是靠谱客的博主 大方山水,这篇文章主要介绍how to write a struct to a file directly?,现在分享给大家,希望可以做个参考。

Using write and read system call. Following is an example:

blk.h:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> struct data{ char s[20]; int d1; char c; }; #define BLK_SIZE 25

writeb.c:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "blk.h" int main(){ struct data *d= malloc(BLK_SIZE); d->d1= 8; d->c= 'a'; strcpy(d->s, "first try.."); int fd= open("blk.dat", O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE); write(fd, d, BLK_SIZE); printf("writed!n"); close(fd); return 0; }

readb.c:

复制代码
1
2
3
4
5
6
7
8
9
10
11
include "blk.h" int main(){ int fd; struct data *d; fd= open("blk.dat", O_RDWR); read(fd, d, BLK_SIZE); printf("%d, %c, %sn", d->d1, d->c, d->s); close(fd); return 0; }

 

转载于:https://www.cnblogs.com/miaoz/p/4001835.html

最后

以上就是大方山水最近收集整理的关于how to write a struct to a file directly?的全部内容,更多相关how内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(88)

评论列表共有 0 条评论

立即
投稿
返回
顶部