open函数的系统调用有两种方式,一种是没有文件创建一个文件并且打开,一种是只有以只读只写等方式打开。以下演示这两种方式的代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <signal.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main()
{
int fd = open("test.txt", O_CREAT);
if(fd == -1)
{
ERR_EXIT("open error");
}
return 0;
}
int fd = open("test.txt", O_CREAT);
这行代码是创建test.txt文件,其实和creat函数一样,都是创建函数,但是creat函数现在不怎用的,因为open函数完全可以代替的。
int fd = open("test.txt", O_RDWR | O_CREAT);
这行代码就是创建文件并且以读写的方式打开。当然还可以或很多参数,这个看个人需要当然要是记不住这些参数可以找一下男人, man 2 open 产看一下。个人原因,英文水平有限,只能看看中文文档。
.
int fd = open("test.txt", O_RDONLY);
这行代码就是以只读的方式打开。如果文件下没有test.txt文件那么就会出错。