**
系统调用函数
**
open系列系统调用-creat
**
int creat(const char* pathname,mode_t mode)
**
例题:在/home/dhh/c.d目录下创建一个tttt.txt文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
void main()
{
int fd=creat("/home/dhh/c.d/tttt.txt",0755);
if(fd==-1)
{
printf("errno:%d\n",errno);
}
else
{
printf("fd:%d,create file successful! ",fd);
}
}
注:0755->即表示用户具有读/写/执行(rwx)权限,组用户和其它用户具有读/执行(r-x)权限。
在程序运行前先ll查看c.d目录下的文件,没有tttt.txt
运行程序,成功,输出create file successful!
再次ll查看c.d目录,tttt.txt已被创建
**
int open(const char* pathname,int flags,mode_t mode)
**
mode_t指的是创建文件权限,比如上面说用到的0775。
flags是指打开文件的方式,一般是文件已经存在,用何种方式打开,一般主要有以下几种方式:
open函数其核心代码为:
int fd=open("/home/dhh/c.d/tttt.txt",O_RDWR|O_CREAT|O_EXCL,0755);
int close(int fd)
注:fd为文件操作符
当我们完成文件操作需要关闭文件,就要用到close函数
例题:打开一个文件然后关闭它
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
void main()
{
int state,fd;
fd=open("/home/dhh/c.d/tttt.txt",O_RDWR|O_CREAT,0755);
if(fd==-1)
{
printf("errno:%d,errno:%s\n",errno,strerror(errno));
exit(EXIT_FAILURE);
}
else
{
printf("fd:%d,open file successful!\n ",fd);
}
state=close(fd);
if(state==0)
{
printf("close file successful!\n");
}
else if(state==-1)
{
printf("errno:%d,errno:%s\n",errno,strerror(errno));
exit(EXIT_FAILURE);
}
}
说明文件被成功打开或关闭,若是出现错误无法打开则可以显示错误的代码和它所对应的错误描述。
Linux系统内核代码中errno的值及其对应的中文意思
/usr/include/asm/errno.h
#define EPERM 1 /* Operation not permitted */操作不允许
#define ENOENT 2 /* No such file or directory */文件/路径不存在
#define ESRCH 3 /* No such process */进程不存在
#define EINTR 4 /* Interrupted system call */中断的系统调用
#define EIO 5 /* I/O error */I/O错误
#define ENXIO 6 /* No such device or address */设备/地址不存在
#define E2BIG 7 /* Arg list too long */参数列表过长
#define ENOEXEC 8 /* Exec format error */执行格式错误