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

文件I/O操作之文件的打开,创建,关闭和定位-基于Linux系统文件IO

时间:2014-09-02 22:52:25      阅读:440      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   io   使用   ar   文件   

1.

打开文件

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

int open(const char *pathname,int flag);    //打开一个现有的文件
int open(const char *pathname,int flags,mode_t mode);   //若文件不存在,则先创建它

//成功则返回文件描述副,否则返回-1
//pathname为文件的相对或绝对路径名

文件描述符从3开始(0,1,2被标准IO占用),依次被分配给打开的文件

flags取值:

O_RDONLY;   //只读
O_WRONLY;  //只写
O_RDWR;  //读写

O_CREAT;
O_EXCL;

O_NOCTTY;
O_TRUNG;
O_APPEND;
O_NONBOLCK;
O_NONELAY;
O_SYNC;

mode取值

S_ISUID;
S_ISGID;
S_SVTX;
S_IRUSR;
S_IWUSR;
S_IXUSR;
S_IRGRP;
S_IWGRP;
S_IXGRP;
S_IROTH;
S_IWOTH;
S_IXOTH;

组合mode

S_IRWXU;
S_IRWXG;
S_IRWXO;

示例:

打开文件

 1 #include<sys/types.h>
 2 #include<sys/stat.h>
 3 #include<fcntl.h>
 4 
 5 #include<stdio.h>
 6 #include<stdlib.h>
 7 #include<string.h>
 8 
 9 #define FLAGS O_WRONLY|O_CREAT|O_TRUNC
10 #define MODES S_IRWXU|S_IXGRP|S_IRGRP|S_IROTH|S_IXOTH
11 
12 int main(void)
13 {
14     const char *pathname;
15     int fd;
16     char pn[30];
17     printf("please input the pathname <30 strings:\n");
18     scanf("%s",pn);
19     pathname=pn;
20     if((fd=open(pathname,FLAGS,MODES))==-1)
21     {
22         printf("error can‘t open file! \n");
23         exit(255);
24     }
25     printf("OK ,file has been open!\n");
26     printf("fd=%d\n",fd);
27     return 0;
28 }

2.

创建文件

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int creat(const char *pathname,mode_t mode);

若成功,返回以只写方式打开的文件描述符,否则返回-1

注意:creat等效于

open(pathname,O_WRONLY|O_CREAT|O_TRUNC,mode);

创建文件并打开的新方式

open(pathname,O_RDWR|O_CREAT|O_TRUNC,mode);

3.

关闭文件

#include<unistd.h>
int close(int fd);

fd是文件描述符,成功返回0,出错返回-1

4.

定位文件

#include<sys/types.h>
#include<unistd.h>
off_t lseek(int fd,off_t offset,int whence);

offset时定位的位移量大小,与whence参数有关

SEEK_SET;   //位移量就是据文件开头的offset字节
SEEK_CUR;   //距当前位置offset字节
SEEK_END;   //距文件尾offset字节

后两个参数允许取offset负值

 

可使用此方法获取文件当前位移量

off_t offset;
offset=lseek(fd,0,SEEK_CUR);

也可时使用此方法测试文件是否能被设置偏移量

 

文件I/O操作之文件的打开,创建,关闭和定位-基于Linux系统文件IO

标签:des   style   blog   color   os   io   使用   ar   文件   

原文地址:http://www.cnblogs.com/lhyz/p/3952403.html

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