【文件I/O】——open

 open

所需头文件

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

函数原型

int open(const char *pathname, int flags);//打开一个已经存在的文件,不存在,则返回-1
int open(const char *pathname, int flags, mode_t mode);//需要创建文件时使用
  • pathname:准备打开的文件或设备的名字。
  • mode:指定创建文件的权限。
  • flags:

1)flags 用于指定打开文件所采取的动作(文件访问模式标志),如只读方式打开、只写方式打开和读写方式打开,这三个模式互斥,只能出现一个。

文件访问模式标志
标志 用途
O_RDONLY 以只读方式打开
O_WRONLY 以只写方式打开
O_RDWR 以读写方式打开

  

如果要打开的文件不存在,又没有使用O_CREAT标志来创建文件时,open函数返回-1,并设置errno。

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

int main()
{
    /* 定义文件描述符并初始化为 -1 */
    int fd = -1; 
    if ((fd = open("open.txt",O_RDONLY)) == -1) 
    {   
        perror("open.txt open failed");
    }                                                                  
    close(fd);
    return 0;
}
View Code
$ ./a.out 
open.txt open failed: No such file or directory

如果文件存在,则按照指定的模式打开,并返回文件描述符。


2)flags 可以是一些文件创建标志以及一些文件状态标志,它们之间使用 “ | ”(或)连接。

O_CREAT:

如果文件不存在,就创建一个新的空文件。即使以只读方式打开,该标志仍然有效;如果文件存在,则打开。如果指定了O_CREAT标志,还应该提供mode参数来请求设定新文件文件的原始权限,否则新文件的权限将会被设置为栈中的某个随机值。当然 mode 参数的设置仅仅是请求设定创建的文件的权限,文件权限值的设定还取决于用户掩码——umask 的值。

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

int main()
{
    int fd = -1;
    /*以只读方式打开文件“open.txt”,如果不存在就创建,指定文件权限为0664*/               
    if ((fd = open("open.txt", O_RDONLY | O_CREAT, 0664)) < 0)
    {
        perror("open file is failed");
    }
    close(fd);
    return 0;
}
View Code
$ ls
a.out  open_2.c
$ ./a.out
$ ls -l
total 16
-rwxrwxr-x 1 shelmean shelmean 8544 Jul 30 22:25 a.out
-rw-rw-r-- 1 shelmean shelmean  385 Jul 30 22:13 open_2.c
-rw-rw-r-- 1 shelmean shelmean    0 Jul 30 22:25 open.txt

 O_EXCL:

当指定O_EXCL 标志时,同时也必须指定 O_CREAT 标志;当只是设定了 O_CREAT 标志时,如果文件存在,就打开,假如我们的本意是创建一个新文件,但是刚好存在一个文件和这个要创建的新文件同名,那么就会打开这个已经存在的文件,那么该文件就会被新的操作破坏掉。在使用 O_CREAT 标志的同时,指定 O_EXCL 标志,当这两个标志都被设定时,打开一个已经存在的文件就会报错,O_EXCL 标志和 O_CREAT结合使用,用来创建一个不存在的新文件。

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

int main()
{
    int fd = -1;
    /*
     * 以只读方式打开文件“open.txt”,如果不存在就创建,
     * 指定文件权限为0664,如果文件存在,则报错                               
     */
    if ((fd = open("open.txt", O_RDONLY | O_CREAT | O_EXCL, 0664)) < 0)
    {
        perror("open file is failed");
    }
    close(fd);
    return 0;
}
View Code
$ ls
a.out  open_3.c  open.txt
$ ./a.out 
open file is failed: File exists

猜你喜欢

转载自www.cnblogs.com/shelmean/p/9387757.html