lovejobs

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1.打开文件的函数open,第一个参数表示文件路径名,第二个为打开标记,第三个为文件权限

 

代码:

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

int main()
{
        int fd;

        fd = open("testopen1",O_CREAT,0777);

        printf("fd = %d\n",fd);

        return 0;


}

效果测试:打印打开文件返回的描述符为3,同时创建了文件testopen1

 2.创建文件函数creat和关闭函数close

使用代码

#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
        int fd;
        if(argc < 2)
        {
                printf("please run use ./app filename\n");
                exit(1);
        }

        fd = creat(argv[1],0777);

        printf("fd = %d\n",fd);
        close(fd);

        return 0;


}

测试结果:

3.写文件函数write,第一个参数表示要写入的文件的描述符,第二个参数表示要写入的内容的内存首地址,第三个参数表示要写入内容的字节数;

写入成功返回写入的字节数,失败返回-1

 

测试代码:

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

int main(int argc,char *argv[])
{
        int fd;
        if(argc < 2)
        {
                printf("please run use ./app filename\n");
                exit(1);
        }

        fd = open(argv[1],O_CREAT | O_RDWR,0777);

        if(fd == -1)
        {
                printf("open file failed!");
                exit(0);
        }

        char *con = "hello world!";

        int num =  write(fd,con,strlen(con));
        printf("write %d byte to %s",num,argv[1]);

        close(fd);

        return 0;


}

结果:hello world!写入hello文件成功

查看当前系统最大打开文件个数

4.读取文件read,第一个参数是文件描述符,第二个参数是存储读取文件内容的内存首地址,第三个参数是一次读取的字节数

测试代码,完成文件复制

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

int main(int argc,char *argv[])
{
        int fd_src,fd_des;
        char buf[1024];

        if(argc < 3)
        {
                printf("please run use ./app srcfilename desfilename\n");
                exit(1);
        }

        fd_src = open(argv[1],O_RDONLY);
        fd_des = open(argv[2],O_CREAT | O_WRONLY | O_TRUNC,0777);

        if(fd_src != -1 && fd_des != -1)
        {
                int len = 0;
                while(len = read(fd_src,buf,sizeof(buf)))
                {
                        write(fd_des,buf,len);
                }

                close(fd_src);
                close(fd_des);
        }


        return 0;

      }

效果查看,可见实现了文件open.c的拷贝

 

posted on 2017-07-21 05:30  lovejobs  阅读(565)  评论(0编辑  收藏  举报