将FILE*转换为Win32文件句柄

HANDLE GetFileHandle(FILE *fp)
{
    int fid = _fileno(fp);

    if (fid != -1)
    {
        intptr_t p = _get_osfhandle(fid);
        if (p)
            return reinterpret_cast<HANDLE>(p);
    }

    return INVALID_HANDLE_VALUE;
}

_fileno

int _fileno(FILE *stream);

_fileno 返回当前与 stream 相关联的文件说明符。

如果 stream 未指定打开的文件,则结果不确定。 如果流为 NULL,_fileno 会调用无效的参数处理程序,如参数验证中所述。 如果允许执行继续,则此函数将返回 -1 并将 errno 设置为 EINVAL。

// This program uses _fileno to obtain
// the file descriptor for some standard C streams.
#include <stdio.h>

int main()
{
   printf( "The file descriptor for stdin is %d\n", _fileno( stdin ) );
   printf( "The file descriptor for stdout is %d\n", _fileno( stdout ) );
   printf( "The file descriptor for stderr is %d\n", _fileno( stderr ) );
}

输出:

The file descriptor for stdin is 0
The file descriptor for stdout is 1
The file descriptor for stderr is 2

_get_osfhandle

intptr_t _get_osfhandle(int fd);

如果 fd 有效,則返回操作系统句柄。将返回值当作Win32文件句柄使用时,为了避免警告,需要将它转换为HANDLE类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值