#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
int fd;
fd=creat("file1",O_RDWR);//
fd=open("file1",O_RDWR|O_APPEND|O_RDWR);
if(fd==-1)
{
printf("error\n");
return;
}
if(close(fd)==0)
{
printf("successfully closed\n");
}
}
一个非常简单的linux下文件的打开和关闭,旨在从基础学起。
首先看creat函数
#include<fcntl.h>
int create(const char *pathname,mode_t mode);
pathname 也就是指定路径下的文件名;
mode 是文件模式 O_RDONLY,O_WRONLY,O_RDWR
open函数
#include<fcntl.h>
int open(const char *pathname,int oflag,...);
oflag可以指定的三个参数 O_RDONLY,O_WRONLY,O_RDWR 只能选择其中一个哦
下面的
O_APPEND每次从文件尾端开始写
O_CREAT如果文件不存在就创建它
O_TRUNC文件截断至0
这三个参数可以指定多个用与或的方式。