文件描述符与文件指针之间的转换

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#define BUFF (1024)

int file2fd(const char * path)
{
    FILE *fp = NULL;
    int fd;
    
    fp  = fopen(path, "r");
    if (fp == NULL)
    {
        perror("open file error.");
        exit(1);
    }
    else
    {
        printf("open file successfully...\n");
    }
    
    fd = fileno(fp);    /*文件指针转换为文件描述符*/
    if (-1 == fd)
    {
        perror("fp to fd error.");
    }
    else
    {
        printf("ok fd = %d\n", fd);
        exit(1);
    }

    return 0;
}

int fd2file(const char * path)
{
    int  fd;
    FILE *fp = NULL;
    fd = open(path, O_CREAT|O_RDWR, 0666);
    if(-1 == fd)
    {
        perror("open file error.");
        return -1;
    }
    else
    {
        printf("ok!\n");
    }
    
    fp = fdopen(fd, "r");       /*文件描述符转换为文件指针*/
    if (NULL == fp)
    {
        perror("fd to fp error.");
    }
    else
    {
        printf("ok!!!!\n");
        return 0;
    }
    
    return 0;
}

int main(int argc, const char *argv[])
{
    int ret = -1;
    char arg[BUFF] = { 0 };
    memset(arg, 0, sizeof(arg));
    strcpy(arg, argv[1]);
    
    ret = fd2file(arg);
    if(ret != 0)
    {
        fprintf(stderr, "fd2file error %d\n", ret);
        return ret;
    }
    puts("\n\n");
    ret = file2fd(arg);
    if(ret != 0)
    {
        fprintf(stderr, "file2fd error %d\n", ret);
        return ret;
    }
    
    return 0;
}


测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值