打开/创建文件
open / creat
包含三个头文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
open函数的函数原型:
int open(const char *pathname,int flags);
int open(const char *pathname,int flags,mode_t mode);
参数:Pathname:要打开的文件名(含路径,缺省为当前路径)
Flags:文件打开权限
O_RDONLY ——只读打开;
O_WRONLY ——只写打开;
O_RDWR ——可读可写打开;
返回值:一个非负整数的文件标识符;
当我们附带了权限过后,打开的文件就只能按照这种权限来操作。
以上三个常数中应当只指定一个。下列常数是可选择的:
O_CREAT 若文件不存在则创建它。使用时,需要说明第三个参数mode,用其说明该新文件的存取许可权限。
O_EXCL 如果同时指定了OCREAT,而文件已经存在,则打开文件失败,返回值是-1
O_APPEND 每次写时都加到文件的尾端。
O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容错误的,而且只读或只写成功打开,则将其长度截短为0。
creat函数原型:
int creat(const char *pathname,mode_t mode);
练习:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd = open("./file1",O_RDWR);
if(fd == -1){
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("creat file1 success\n");
}
}
printf("fd = %d\n",fd);
return 0;
}