Linux系统编程——文件编程(一)文件的创建 打开 关闭

212 阅读4分钟

1、创建(creat)

创建文件可以用creat函数,也可以用和open函数进行创建。

首先来看一下 creat 函数

creat函数的头文件为

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

creat函数原型为

int creat(const char *pathname, mode_t mode)

pathname:指向文件路径的指针,要创建的文件名
mode:创建的文件模式,系统自带四个宏,可读可写可执行

S_IRUSR : 可读
S_IWUSR:可写
S_IXUSR:可执行
S_IRWXU:可读、可写、可执行
数字分别表示为:4、2、1、7

int main()
{
	int fd;
//  fd = creat("/home/LWL/liwanliang/file1",S_IRWXU);  绝对路径
    fd = creat("./file6",S_IRWXU);  //当前路径
    if(fd != -1){
    	printf("file created successfully\n");
    }
    return 0;
}
fd = creat("/home/LWL/liwanliang/file1",S_IRWXU);

代表在绝对路径/home/LWL/liwanliang/file1下创建文件file6,并且file6为可读,可写可执行的文件

./file6就代表当前路径下创建文件file6为可读,可写可执行的文件
在这里插入图片描述
在这里插入图片描述
r w x分别表示可读,可写,可执行

返回值

函数返回值为文件描述符

文件描述符可点这里文件描述符

成功:返回一个非负数

失败返回 -1

对一个文件的操作都需要用文件描述符来操作,比如write和read函数

write和read函数可点这里read和write函数

2、打开(open)

open函数的头文件和creat函数一样

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

open函数的函数原型有两个

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

pathname:一个字符串指针,表示要打开的文件名(文件路径)

flags:文件权限

O_RDONLY : 只读打开
O_WRONLY : 只写打开
O_RDWR : 可读可写打开

当附带了权限后,打开的文件就只能按照这种权限来操作

上面三个权限只能指定一个,不能同时选择多个,下面几种权限可多选
O_CREAT :若文件不存在则创建它,使用时需要说明第三个参数mode,用来说明该新文件的读写权限

int main()
{
	int fd;
    fd = open("./file1",O_RDWR);
    if(fd == -1){
    	fd = open("./file1",O_RDWR | O_CREAT,0600);
    	if(fd > 0){          
    		printf("creat success\n");
    	}
    }
    return 0;
}

当file1文件不存在而打开失败后就在当前路径创建一个file1文件,fd = open("./file1",O_RDWR | O_CREAT,0600)就代表创建文件,O_RDWR 和 O_CREAT用 " | "来连接,0600就表示新文件的读写权限,0600表示可读可写

O_EXCL:如果同时指定O_CREAT,而文件已经存在,则出错(返回-1)

fd = open("./file1",O_RDWR | O_CREAT | O_EXCL,06000);//如果file1文件已经存在,fd = -1

如果file1文件已经存在,fd = -1,这样就可以用来判断是否有该文件

if(fd = -1){
    printf("have file1\n");
    }else{
        printf("NO file1\n");
    }

O_APPEND: 每一次写时都加到文件的尾端

fd = open("./file1",O_RDWR | O_APPEND);
int main()
{
    int fd;
    char* buf = "hello world!";
    fd = open("./file1",O_RDWR | O_APPEND);
    //fd = open("./file1",O_RDWR);    
    printf("open susceess fd = %d\n",fd);
    int n_write = write(fd,buf,strlen(buf));
    if(n_write != -1){
    	printf("write %d byte to file1\n",n_write);
     }
     close(fd);
     return 0;
}

在file1文件中已经写好了数据的(随便写的)
在这里插入图片描述
当运行上面代码后file1文件变为
在这里插入图片描述
也就是写入的数据从file1的后面开始,不会影响原来的数据

如果没有O_APPEND,就会将原来的数据覆盖
如下:

fd = open("./file1",O_RDWR);

在这里插入图片描述
O_TRUNC :去打开文件时,如果这个文件中本来是有内容的,而且为只读或者只写成功打开,则将长度截短为0

fd = open("./file1",O_RDWR | O_TRUNC);

简单来说就是源文件将目标文件覆盖,在目标文件中只有源文件文件的数据

mode : 一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限,在上面已经用到

0100:可执行
0200:可写
0400:可读
0600:可读,可写:
0700:可读,可写,可执行

返回值

open函数的返回和creat函数的返回值一样,都返回文件描述符

成功:返回一个非负整数

失败返回 -1

3、关闭(close)

头文件

#include <unistd.h>

函数原型

int close(int fd);

将要关闭的文件描述符传入close函数中即可