文件描述符

xiaoxiao2021-02-28  92

先从对于文件的打开方式着手,fopen,open这两种,fopen是库函的接口,open是操作系统的接口,其原型如下:

FILE * fopen ( const char * filename, const char * mode );

返回值:是一个FILE*的指针,文件顺利打开后,指向该流的文件指针就会被返回。如果文件打开失败则返回NULL,并把错误代码存在errno 中;

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

返回值:是一个整形,以后对这个整形的操作就是对文件的操作,这个整形就是文件描述符。失败返回-1;

#include<stdio.h> #include<sys/types.h> #include<string.h> #include<sys/stat.h> #include<fcntl.h> int main() { int fd = open("./log",O_WRONLY/O_CREAT,644); if (fd < 0) { perror("open\n"); return 1; }else{ char *m = "hello\n"; //write to log write(fd,m,strlen(m)); printf("fd: %d\n",fd); } return 0; }

运行截图:

我们可以看出fd(文件描述符)的值是3,那么是怎么根据3去找到对应的文件并且写入呢?不由得我们就想到了数组,对就是用数组来实现的,数组中存放的是描述该文件的文件对象的地址。

为什么第一个文件的文件描述符是3呢?其实这不是打开的第一个文件,一个程序运行时会默认打开三个文件,stdin(标准输入),stdout(标准输出),stderr(标准错误),这三个就依次占据了0,1,2这三个位置,所以自己打开的文件就从第三个开始排;如果把前三个的某一个关闭,在自己打开一个文件,那么这个文件的文件描述符是多少呢?

#include<stdio.h> #include<sys/types.h> #include<string.h> #include<sys/stat.h> #include<fcntl.h> int main() { close(0); //关闭stdin文件 int fd = open("./log.txt",O_WRONLY/O_CREAT,644); printf("fd: %d\n",fd); if (fd < 0) { perror("open\n"); return 1; }else{ char *m = "hello\n"; //write to log write(fd,m,strlen(m)); } return 0; }

这次的fd变成了0,说明文件描述符的分配是0~n中最小未被使用的来做文件描述符;可以用不同的文件描述符改写默认的设置并重定向。比如,关掉1,本来是往显示屏写,写到了代替0这个位置的文件中,就叫输出重定向;

转载请注明原文地址: https://www.6miu.com/read-26860.html

最新回复(0)