创建文件需要包含以下3个头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
打开、创建文件有以下3个API
open的返回值——文件描述符(索引作用),是一个小的非负整数
int open(const char*pathname,int flags);
int open(const char*pathname,int flags,mode_t mode);
int creat(const char*pathname,mode_t mode);
pathname 要打开的文件名(含路径,缺省为当前路径)
flags:权限:O_RDONLY只读打开, O_WRONLY只写打开, O_RDWR可读可写打开
当我们附带了权限后,打开的文件就只能按照这种权限来操作,以上3个常数中应当只指定1个。
下列常数是可选择的:
O_CREAT若文件不存在则创建它。使用此选项时,需要同时说明第三个参数mode,用其说明该新文件的存取许可权限。
O_EXCL如果同时指定了O_CREAT,而文件已存在,则出错返回-1。
O_APPEND每次写时都加到文件的尾端。
O_TRUNC属性去打开文件时,如果这个文件中本来时有内容的,而且为只读或只写成功打开,则将其长度截短为0.
mode:flages中使用了O_CREAT标志,mode记录待创建的文件的访问权限。
1、O_EXCL使用代码演示:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd;
fd=open("./file1",O_RDWR|O_CREAT|O_EXCL,0600);
if(fd==-1){
printf("file1 cunzai\n");
}
return 0;
}
编译运行结果为:
如果文件不存在,则运行此代码,创建出新的file1文件,如果文件存在,则返回-1
打印出:file1 cunzai
能够检测文件是否存在
2、O_APPEND的用法,代码演示
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf="yangzeruihenshuai!";
fd=open("./file1",O_RDWR|O_APPEND);
int n_write=write(fd,buf,strlen(buf));
if(n_write!=-1){
printf("write %d byte to file1\n",n_write);
}
}
CLC@Embed_Learn:~$
在打开文件操作flag上|O_APPEND,会将光标移到最后下一行
在原有文件下一行开始进行操作
如果没有添加APPEND这个参数,新写入的数据会覆盖之前的数据
3、O_TRUNC使用,代码演示
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
char *buf="text";
fd=open("./file1",O_RDWR|O_TRUNC);
printf("open successed :fd=%d\n",fd);
// ssize_t write(int fd, const void *buf, size_t count);
int n_write=write(fd,buf,strlen(buf));
printf("write %d byte to file1",n_write);
close(fd);
return 0;
}
编译运行结果,会将原先文件中的内容抹去,写入新的内容,这里是text
4、creat用法
需要包含头文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
creat函数的API
int creat(const char *pathname, mode_t mode);
parhname:要创建的文件名(包含路径,缺省为当前路径)
mode:创建模式 //可读、可写、可执行
S_IRUSR——4——可读
S_IWUSR——2——可写
S_IXUSR——1——可执行
S_IRWXU——7——可读、写、执行
代码演示:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
char *buf="text";
// int creat(const char *pathname, mode_t mode);
fd=creat("/home/CLC/file1",S_IRWXU);
return 0;
}
编译执行
pwd进入绝对路径,
ls可以看到目录有个绿色file1
ls -l可以看到文件时权限为rwx,可读、可写、可执行