#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
struct Student
{
char name[20];
int age;
char sex;
};
int main()
{
struct Student s1 = {"aaa",20,'a'};
struct Student s2 = {"eee",30,'b'};
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(s2));
if(-1 == ret)
{
perror("write");
exit(1);
}
fd = open("Student.txt", O_RDONLY);
if (-1 == fd)
{
perror("open");
exit(1);
}
struct Student s;
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;
}