open、write、read函数及应用


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
typedef struct students
{
    int num;
    char name[20];
    struct students *next;
}Stu,*PStu;
PStu head=NULL;
PStu r;
//-----写入链表-----
void creat_list(PStu *phead,PStu r)// 需要把读取到的最后一个节点指针传参进来
{
    PStu ptr;
    char choose;
    int num;
    char name[20];
    while(1)
    {
        printf("do you want to add a student?(y or else)\n");
        scanf("%c",&choose);getchar();
        if(choose=='y')
        {
            ptr=malloc(sizeof(Stu));
            printf("id=");
            scanf("%d",&num);getchar();
            printf("name=");
            scanf("%s",name);getchar();
            ptr->num=num;
            strcpy(ptr->name,name);
            ptr->next=NULL;
            if(*phead==NULL)//如果没有读取到,则从头开始创建
            {
                *phead=ptr;

            }
            else
                r->next=ptr;
            r=ptr;
        }

        else if(choose!='y')
            break;
    }
}
//-----打印函数-----
void printf_list(PStu ptr)
{
    while(ptr!=NULL)//无头节点
    {
        printf("%d\t%s\n",ptr->num,ptr->name);
        ptr=ptr->next;
    }
}
//-------读文件------
PStu read_file(PStu *head)
{
    int fd;
    int ret;
    PStu p,r;
    fd=open("./stu.txt",O_CREAT|O_RDONLY,00700);
    if(fd<0)
    {
        perror("open");exit(0);

    }
    else
    {
        while(1)
        {
            p=malloc(sizeof(Stu));
            ret=read(fd,p,sizeof(Stu));//从文件中读取内容存在(节点)指针中
            if(ret<0)
            {
                perror("read");break;
            }
            if(ret==0)//read返回值为0时结束
            {
                printf("-------read over------\n");
                break;
            }
            if(ret>0)//read返回值>0时循环读取并往后移动
            {
                p->next=NULL;
                if(*head==NULL)
                {
                    *head=p;
                }
                else
                    r->next=p;
                r=p;
            }
        }
    }
    close(fd);return r;//返回读取到的最后一个节点指针
}
//-----写文件------
void write_file(PStu p)
{
    /*  read_file(PStu *ptr);*/
    int fd;
    int ret;
    fd=open("./stu.txt",O_WRONLY);
    if(fd<0)
    {
        perror("open");
        return ;
    }
    for(;p!=NULL;p=p->next)
    {
        ret=write(fd,p,sizeof(Stu));
        if(ret<0)
            perror("write");
    }
    close(fd);
}
//------主函数-----
int main()
{
    r=read_file(&head);//得到所读取到的最后一个节点指针
    PStu p;
    creat_list(&head,r);
    write_file(head);
    if(head==NULL)
        printf("无学生\n");
    else
    {
        printf("学号\t姓名\n");
        printf_list(head);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/IT8343/article/details/80822588