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


pathname 参数就是要打开或创建的文件名,可以是绝对路径也可以是相对路径。

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
原创粉丝点击