Linux下的文件流和文件描述符

文件流

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;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值