版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
一、文件描述符
文件描述符是一个非负整数,表示一个打开的文件,内核中有三个特殊的文件描述符,“stdin”,“stdout”,“stderr”,他们所对应的值为0,1,2,他们能的宏定义在unistd.h头文件当中。
由于记录文件相关信息的结构体记录在内核当中,为了不暴露内核的地址,因此文件结构体指针不能直接给用户直接使用。而内核中会存在一张表记录文件描述符和他对应文件指针,因此文件描述符就相当于是文件指针的下标。
二、creat/open/close 函数
1、头文件
#Include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
2、creat函数
int creat(const char *pathname, mode_t mode);
//功能 :创建一个文件
//参数1:创建文件的路径
//参数2:创建文件的权限
//mode:设置文件的存储权限
//USR用户的权限 X:可执行,R:读权限,W写权限
//S_IRWXU 00700 read,write and execute permission
//S_IRUSR 00400 user has read permission
//S_IWUSR 00200 user has write permission
//S_IXUSR 00100 user has execute permission
//GRP组的权限 X:可执行,R:读权限,W写权限
//S_IRWXG 00070 read,write and execute permission
//S_IRGRP 00040 group has read permission
//S_IWGRP 00020 group has write permission
//S_IXGRP 00010 group has execute permission
//OTH其他用户的权限 X:可执行,R:读权限,W写权限
//S_IRWXO 00007 others have read, write and
//S_IROTH 00004 others have read permission
//S_IWOTH 00002 others have write permission
//S_IXOTH 00001 others have execute permis‐sion
//返回值:成功返回文件描述符,失败返回-1
使用方法:
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
int fd = creat("./test.txt",0644);
printf("%d\n",fd);
}
//在当前路径下创建一个test.txt文件,用户具有读写权限,组和其他用户只有读权限
3、open函数
int open(const char *pathname, int flags);
//功能:打开一个文件
//参数1:文件路径
//参数2:打开文件的方式
//O_WRONLY 以只写的方式打开
//O_RDONLY 以只读的方式打开
//O_RDWR 以读写的方式打开
//O_APPEND 写的方式打开后追加到文件末尾
//O_TRUNC 写的方式打开,清空文件数据
//O_CREATE 创建一个文件与create()函数功能大致相同
//O_EXCL 如果文件存在则失败通常配合O_CREATE使用
int open(const char *pathname, int flags, mode_t mode);
//多了一个mode参数表示创建文件的权限,当参数2为O_CREATE必须要加mode参数。
使用方法
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
int fd1 = open("./open.txt",O_CREAT|O_EXCL|O_RDWR,0644);//创建一个open.txt文件
//int fd2 = open("./open.txt",O_RDWR); 以读写的方式打开一个文件
printf("%d",fd);
}
4、close函数
int close(int fd);
//功能:关闭文件
//参数:文件描述符
//返回值:关闭成功返回0,否则返回-1
三、read\write函数
1、write函数
ssize_t write(int fd, const void *buf, size_t count);
//功能将数据写入到文件中
//参数1:要写入的文件描述符
//参数2:要写入的数据地址
//参数3:要写入的字节数
//返回值:成功写入的字节数
使用方法:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
int fd = open("./write.txt",O_WRONLY|O_CREAT,0644);
if(fd < 0)
{
perror("open");
return -1;
}
char buf[1024] = "hello world";
int ret = write(fd,buf,strlen(buf));
printf("ret=%d\n",ret);
}
2、read函数
ssize_t read(int fd, void *buf, size_t count);
//功能从文件中读取数据
//参数1:要读取的文件描述符
//参数2:读取的数据存储到buf
//参数3:读取的字节数
//返回值:成功读取到字节数
使用方法
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
int fd = open("./write.txt",O_RDONLY);
if(fd < 0)
{
perror("open");
return -1;
}
char buf[1024] = {};
read(fd,buf,sizeof(buf));
puts(buf);
}