open 和 close 函数
来源:互联网 发布:小型机房网络拓扑 编辑:程序博客网 时间:2024/04/27 21:03
open函数可以打开或创建一个文件,close 函数就是关闭文件了。
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int open(const char *pathname, int flags);int open(const char *pathname, int flags, mode_t mode);返回值:成功则返回新分配的文件描述符,出现错误就返回 -1
flag 参数有多种选择:
必选项:
- O_RDONLY 只读打开
- O_WRONLY 只写打开
- O_RDWR 可读可写打开
可选项:
- O_APPEND 表示追加。如果文件已有内容,这次打开文件所写的数据附加到文件的末尾而不覆盖原来的内容。
- O_CREAT若此文件不存在则创建它。使用此选项时需要提供第三个参数mode,表示该文件的访问权限。
- O_EXCL如果同时指定了O_CREAT,并且文件已存在,则出错返回。
- O_TRUNC如果文件已存在,并且以只写或可读可写方式打开,则将其长度截断(Truncate)为0字节。
- O_NONBLOCK对于设备文件,以O_NONBLOCK方式打开可以做非阻塞I/O(Nonblock I/O)
mode参数:
指定文件权限,4位数字,第一位一般是0 后面三位是 r w x 4 2 1 一般用八进制表示,方便记忆。
Close 函数:
#include <unistd.h>int close(int fd);返回值:成功返回0,出错返回-1并设置errno
虽然进程终止后,系统会自动清理残余的文件描述符。但是每次打开资源,退出时关闭资源也不失为一个良好的习惯。
#include <stdio.h>#include <sys/stat.h>#include <sys/types.h>#include <fcntl.h>#include <unistd.h>int main(){int fd;fd = open("./hello.txt", O_CREAT | O_WRONLY);if(fd > 0){printf("open file successfully\n And fd = %d\n", fd);}else{perror("./hello.txt");}close(fd);return 0;}输出:open file successfully And fd = 3
0 0
- open 和 close 函数
- 浅析open、close函数
- open和close
- 文件IO编程之open和close函数使用实例
- Linux系统函数open和close(01)
- open、close以及creat函数
- open/close函数的使用
- open() close() 函数的使用
- open/close函数的使用
- chmod()函数和fchmod()函数,open()函数和creat()函数,close()函数,umask命令
- Linux系统函数open和close(02)---open函数的返回值
- Linux系统函数open和close(03)---open函数的参数
- Linux系统函数open和close(04)---open函数错误信息获取
- Linux系统函数open和close(04)---open函数错误信息获取
- window.open和window.close
- open函数,create函数,close函数
- (七)umask掩码、open函数和close函数的使用
- linux下 open() write() read() close函数
- 网络测试笔记1
- 在Windows窗体中显示OpenCV图像
- 获取新浪微博api授权
- 第135课: Spark面试经典系列之数据倾斜:数据倾斜是多么痛?!
- 剑指offer41--扑克牌顺序
- open 和 close 函数
- 构造函数初始化、static代码块初始化、成员变量初始化、以及在子父类中混合的执行顺序实例
- hrbust 1131 波动序列【水题】
- RFID-RC522 与Arduino的连接
- Visual Studio Graphics Debugger
- 1045. Favorite Color Stripe
- java8collection
- 从今天起写技术博客
- iOS开发 - 第04篇 - 网络 - 01 - NSOperation & 网络基础