码迷,mamicode.com
首页 > 系统相关 > 详细

linux系统编程之文件IO

时间:2017-07-21 10:35:43      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:img   文件权限   lib   hello   while   编程   turn   文件io   创建   

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的拷贝

技术分享

 

linux系统编程之文件IO

标签:img   文件权限   lib   hello   while   编程   turn   文件io   创建   

原文地址:http://www.cnblogs.com/huipengbo/p/7215720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!