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

Linux的文件I/O

时间:2016-06-29 23:31:49      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

int open(const char *pathname, int flags, mode_t mode);

    #include <sys/types.h>
           #include <sys/stat.h>
           #include <fcntl.h>
            参数1:要打开的文件
            参数2:打开类型,O_RDONLY,O_WRONLY, O_RDWR,O_CREAT,O_EXCL,O_TRUNC,O_APPEND
                      O_TRUNC 清空文件, CREAT | O_TRUNC 文件不存在则创建,存在则清空文件内容
                      O_EXCL 测试文件是否存在,与O_CREAT连用
            参数3:文件的权限,例如0660(八进制)
            返回值:文件描述符,非负整数, 出错返回-1
            

ssize_t read(int fd, void *buf, size_t count);
    #include <unistd.h>            

     参数1:open成功后打开的描述符
            参数2:读文件后存放数据的buf
            参数2:buf所占的字节数
            返回值:-1 出错,0 文件结束,大于0 读到的字节数
            
           

ssize_t write(int fd, const void *buf, size_t count);
            参数1:open成功后打开的描述符
            参数2:写入文件存放数据的buf
            参数3:写入文件的字节数
            返回值:-1出错,0 未写入文件, 大于0 成功写入文件的字节数
        
 int close(int fd);
            关闭文件
            参数1:打开的文件描述符
            返回值:0 成功, -1 出错。
            
 int stat(const char *path, struct stat *buf);
            功能:获取文件信息
            参数1:文件路径
            参数2:存放文件信息结构体
            返回值: -1出错,0 成功
            #include <sys/types.h>
            #include <sys/stat.h>
            #include <unistd.h>

 //自编copy函数
1
#include <stdio.h> 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <fcntl.h> 5 #include <unistd.h> 6 #include <stdlib.h> 7 #define BUF_SIZE 12 8 9 int main(int argc ,char *argv[]) 10 { 11 //open file 12 if(argc !=3||NULL== argv[2]||NULL== argv[1]) 13 { 14 printf("please input file"); 15 return -1; 16 } 17 char buf[BUF_SIZE]={0}; 18 19 /*char data[]={}; 20 printf("please input write data"); 21 scanf("%s",data);*/ 22 23 int fd1=open(argv[1],O_RDWR|O_CREAT,0664); 24 if(-1==fd1) 25 { 26 perror("open"); 27 exit(EXIT_FAILURE); 28 } 29 int fd2=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0664); 30 if(-1==fd2) 31 { 32 perror("open"); 33 exit(EXIT_FAILURE); 34 } 35 //read file 36 size_t count=BUF_SIZE; 37 int iRed=0; 38 while((iRed=read(fd1,buf,count))>0) 39 { 40 ssize_t iWrite=write(fd2,buf,iCount); 41 if ( -1 == iWrite) 42 { 43 perror ("write"); 44 exit (EXIT_FAILURE); 45 } 46 } 47 //close file 48 if(-1==close(fd1)) 49 { 50 perror("close"); 51 exit(EXIT_FAILURE); 52 } 53 if(-1==close(fd2)) 54 { 55 perror("close"); 56 exit(EXIT_FAILURE); 57 } 58 return 0; 59 60 }

 

Linux的文件I/O

标签:

原文地址:http://www.cnblogs.com/t-code/p/5628345.html

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