加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux文件操作篇 (二) 打开和关闭文件

发布时间:2020-12-14 02:07:59 所属栏目:Linux 来源:网络整理
导读:2.1 打开文件和关闭文件 #include sys/types.h #include sys/stat.h #include fcntl.h ? int open(const char *pathname,intflags); ? int open(const char *pathname,intflags,mode_tmode); ? ?int creat(const char *pathname,mode_tmode); ? ?int close(i

2.1 打开文件和关闭文件

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
?
int open(const char *pathname,intflags);
?

int open(const char *pathname,intflags,mode_tmode);

?
?int creat(const char *pathname,mode_tmode); ?
?int close(int fildes); ? ? ?
? ?
? ?
? ?

?

?













intopen(constchar*pathname,?intflags);
//const char *pathname 是要打开的文件路径
//int flag 是文件打开的标志 。 标志有 主标志 和 副标志 。
//主标志是互斥的。三选一
//O_RDONLY只读方式打开
//O_RDWR读写方式打开
//O_WRONLY只写方式打开
//副标志可以多选
//O_APPEND--> 读写文件从文件末尾处追加
//O_TRUNC--> 若文件存在并可写,则用清空的方式打开文件
//O_CREAT--> 若文件不存在,则创建该文件
//O_EXCL--> ??
?
//如果用O_CREAT 方式创建不存在的文件,open则需要额外设置文件权限
intopen(constchar*pathname,?intflags,?mode_tmode);
//mode_t mode 用0755 或者其他权限写入即可 .?
//创建文件的另一个函数,用法同open
intcreat(constchar*pathname,?mode_tmode);
//在使用完文件后,必须正常关闭文件!!
close(fd);

举个栗子:

/*
============================================================================
Name ? ? ? : hello.c
Author ? ? :?
Version ? ? :
Copyright ? : Your copyright notice
Description : Hello World in C,Ansi-style
============================================================================
*/
?
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>?//open
#include <unistd.h>?//close
?
intmain(void)
{
intfd;
constchar*file="./hello";
?
fd=open(file,O_RDWR);
if(fd<0)
{
puts("no such file .");
fd=open(file,O_RDWR|O_CREAT,0755);
if(fd<0)
{
puts("open file err !");
return-1;
}
}
puts("open file success .");
?
close(fd);
puts("close file success .");

returnEXIT_SUCCESS;
}
?
?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读