文件流
Linux下的库函数通过流对象来使用文件。
//fp对应的是filename的流对象,进程通过fp来操作文件
FILE *fp;
fp=fopen(filename,"r");
close(fp);
每个进程都有三个默认的流对象:stdin, stdout, stderr.
文件描述符
系统调用通过文件描述符来使用文件。
文件描述符:每个打开文件对应的一个惟一非负整数。
流对象对应的文件描述符:
stdin:0 stdout:1 stderr:2
之后打开的文件描述符的值一般选取未使用的最小值。
两者之间的转换
流对象和文件描述符是可以相互转换的。
1>流对象->文件描述符
//库函数
#include<stdio.h>
//函数原型
int fileno(FILE *stream) //stream为要转换的流对象
//返回值
成功返回文件描述符
失败返回-1
#include<stdio.h>
int main(){
printf("stdin is:\t%d\n",fileno(stdin));
printf("stdout is:\t%d\n",fileno(stdout));
printf("stderr is:\t%d\n",fileno(stderr));
return 0;
}
2>文件描述符->流对象
//库函数
#include<stdio.h>
//函数原型(fd:要转换的文件描述符 mode:访问模式)
FILE *fdopen(int fd, const char *mode)
//返回值
成功返回流对象
失败返回NULL
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
int main(){
int fd;
FILE *stream;
fd=open("test.txt",O_CREAT|O_WRONLY,S_IREAD|S_IWRITE);
//访问模式必须与文件描述符相符
stream=fdopen(fd,"w");
if(stream==NULL)
printf("fdopen error.");
else{
fprintf(stream,"this is to test fdopen.\n");
fclose(stream);
}
return 0;
}