您的位置:首页 > 运维架构 > Linux

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

2014-09-02 22:18 477 查看
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;


示例:

打开文件

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

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define FLAGS O_WRONLY|O_CREAT|O_TRUNC
#define MODES S_IRWXU|S_IXGRP|S_IRGRP|S_IROTH|S_IXOTH

int main(void)
{
const char *pathname;
int fd;
char pn[30];
printf("please input the pathname <30 strings:\n");
scanf("%s",pn);
pathname=pn;
if((fd=open(pathname,FLAGS,MODES))==-1)
{
printf("error can't open file! \n");
exit(255);
}
printf("OK ,file has been open!\n");
printf("fd=%d\n",fd);
return 0;
}


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);


也可时使用此方法测试文件是否能被设置偏移量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: