将结构体数据保存写入到文件中

利用系统接口,将结构体数据写入到文件中。

/***********************************
  File Name: copy.c
  Author: Lifengyu
  Created Time: 2018.8.13
 ***********************************/

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

struct Student
{
	char name[20];
	int age;
	char sex;
};

int main()
{
	struct Student s1 = {"aaaa", 20, 'm'}; //定义两个结构体
	struct Student s2 = {"bbbb", 30, 'f'};

	int fd = open("Student.txt", O_WRONLY | O_CREAT | O_EXCL, 0666);
    //以只写方式打开一个文件,若不存在就创建,若存在就打开已有文件,给创建赋予权限

	if (-1 == fd)
	{
		perror("open");
		exit(1);
	}

	int ret = write(fd, (void *)&s1, sizeof(s1));
	if (-1 == ret)
	{
		perror("write");
		exit(1);
	}

	ret = write(fd, (void *)&s2, sizeof(s1));
	if (-1 == ret)
	{
		perror("write");
		exit(1);
	}

	struct Student s;
	
	fd = open("Student.txt", O_RDONLY);
	if (-1 == fd)
	{
		perror("open");
		exit(1);
	}

	while (1)      //用循环写入数据
	{
		ret = read(fd, (void *)&s, sizeof(s));
		if (-1 == ret)
		{
			perror("read");
			exit(1);
		}
		if (ret == 0)
		{
			break;
		}
		printf("%s %d %c\n", s.name, s.age, s.sex);
		memset(&s, 0, sizeof(s));
	}

	close(fd);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wow66lfy/article/details/81636823