文件系统调用:
open、close、create、read、write
open:
int open(const char* path, int flags)
path:要打开的文件的路径
flags:打开的模式
执行结果:成功返回文件描述符,失败返回-1。
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> #include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h> //普通的宏定义写法,多条语句用逗号表达式。
//#define ERR_EXIT(m) (perror(m), exit(EXIT_FAILURE)) //这种宏定义的写法更为专业,工作中都是用这种
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while() int main(void)
{
int fd;
fd = open("test.txt", O_RDONLY);
/*
if (fd == -1)
{
fprintf(stderr, "open error with errno=%d %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
*/
/*
if (fd == -1)
{
perror("open error");
exit(EXIT_FAILURE);
}
*/
if (fd == -)
ERR_EXIT("open error"); printf("open succ\n");
return ;
}
int open(const char *path, int flags,mode_t mode);
打开成功,返回文件描述符;
打开失败,返回-1
打开方式 |
描述 |
O_RDONLY |
打开一个供读取的文件 |
O_WRONLY |
打开一个供写入的文件 |
O_RDWR |
打开一个可供读写的文件 |
O_APPEND |
写入的所有数据将被追加到文件的末尾 |
O_CREAT |
打开文件,如果文件不存在则建立文件 |
O_EXCL |
如果已经置O_CREAT且文件存在,则强制open()失败 |
O_TRUNC |
在open()时,将文件的内容清空 |
其中注意打开的文件的权限不是mode而是mode&^umask。
自己可以用umask命令查看当前的umask值,在程序中也可以用umask()来指定umask的值,例如:umask(0)。
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> #include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h> #define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) int main(void)
{
umask(0);
int fd;
fd = open("test.txt", O_WRONLY | O_CREAT | O_EXCL, 0666);
if (fd == -1)
ERR_EXIT("open error"); printf("open succ\n");
return 0;
}
权限可以用数字的形式也可以用下面这种,不过数字更直观一点。
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> #include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h> #define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) int main(void)
{
umask(0); //在程序中自己指定umask值
int fd;
fd = open("test2.txt", O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd == -1)
ERR_EXIT("open error"); printf("open succ\n");
close(fd); //养成好习惯不用了就关闭掉
return 0;
}
如打开一个新文件:
#define NEWFILE (O_WRONLY|O_CREAT|O_TRUNC)
#include <sys/stat.h> 访问到,同样可以通过|运算来对访问权限进行组合
#define MODE755 (S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)