关于close函数和cp命令

来源:互联网 发布:mysql登录数据库命令 编辑:程序博客网 时间:2024/06/16 00:17
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{
    int fd;
    close(1);//这个是关闭了文件标志符为1的文件
    fd = open("./hello",O_RDWR|O_CREAT,0666);//fd是记录了系统返回的所新建的并打开的文件标识符
    if(-1 == fd)
    {
        perror("open error");
        return -1;
    }

    printf("fd is %d\n",fd);//此时输出的fd为1,因为是顺序依次的第一个

    return 0;
}



/*
 ============================================================================
 Name        : cp.c
 Author      :
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include<errno.h>

int write_buffer(int fd,const void *buf,size_t count)
{
    int n=0,r=count;
    while(count>0)
    {
        n=write(fd,buf,count);
        if(n==0)
        {
            r=0;
            break;
        }
        if(n>0)
        {
            count-=n;
            buf+=n;
        }
        else if(n<0)
        {
            if(errno==EINTR)
            {
                continue;
            }
            r=-1;
            break;
        }
    }
}


int main(int argc,char **argv) {//char *argv[],指针数组,存放指针的数组
    int fd1,fd2;
    char buf[128];
    int readnu,writenu;
    if(argc!=3)
    {
        printf("you should enter 3 ");
        return -1;
    }
    fd1=open(argv[1],O_RDONLY);//按只读方式打开这个源文件,一般只有创建的时候才有三个参数
    if(fd1==-1)
    {
        perror("source file wrong");
        return -1;
    }
    fd2=open(argv[2],O_CREAT|O_WRONLY|O_TRUNC,0666);//如果要复制的那个文件是存在的则用O_TRUNC清除,如果不存在,以只写方式写入,没有则可以创建的
    if(fd2==-1)
    {
        perror("copy file wrong");
        close(fd1);//如果第二个文件读取不成功,则返回之前把第一个文件给关闭了
        return -1;
    }
    while(readnu=read(fd1,buf,sizeof(buf)))//这是循环读取数据,把每次读取的字符写道文件中去
    {
        if(readnu>0)//当每次成功读取到数字的时候
        {
            writenu=write_buffer(fd2,buf,readnu);//readnu这里必须要写成这个,为了防止出错
            if(writenu==-1)
            {
                return -1;
            }
            else if((readnu==-1)&&(errno!=EINTR))//        EINTR 此调用被信号所中断。
            {
                break;
            }
        }
    }
    close(fd1);
    close(fd2);
    return EXIT_SUCCESS;
}
//创建文件111
//在终端下编译:gcc cp.c
//然后 a.out 111 222
//检验 diff 111 222如果不一样会出新提示符


原创粉丝点击