有没有办法为fscanf实现包装函数?

时间:2015-08-10 07:00:07

标签: c++ wrapper

我试图为所有文件操作编写包装函数。但是我无法为fscanf实现包装函数。我自己的功能是这样的:

scan(const char * _Format, ... )
{
    va_list args;
    va_start(args, _Format);
    int result = ::fscanf(_ptr, _Format, args);
    va_end(args);
    return result;
}

3 个答案:

答案 0 :(得分:4)

您需要使用vfscanf。请参阅more on vfscanf

int scan(const char * _Format, ... )
{
    va_list args;
    va_start(args, _Format);
    int result = ::vfscanf(_ptr, _Format, args);
    va_end(args);
    return result;
}

答案 1 :(得分:3)

除了vfscanf使用va_list之外,你可以使用variadic模板:

template <typename ... Ts>
int scan(const char* format, Ts&&... args)
{
    int result = ::fscanf(_ptr, format, std::forward<Ts>(args)...);
    return result;
}

答案 2 :(得分:0)

对于那些必须使用比C ++ 11更旧的标准的人,你可以实现自己的vfscanf函数,如下所示:

 int vfscanf(FILE* file, const char *format, va_list argPtr)
{
    size_t count = 0;
    const char* p = format;

    while(1)
    {
        char c = *(p++);
        if (c == 0) 
            break;

        if (c == '%' && (p[0] != '*' && p[0] != '%')) 
            ++count;
    }

    if (count <= 0)
        return 0;

    int result;

    _asm
    {
        mov esi, esp;
    }

    for (int i = count - 1; i >= 0; --i)
    {
        _asm
        {
            mov eax, dword ptr[i];
            mov ecx, dword ptr [argPtr];
            mov edx, dword ptr [ecx+eax*4];
            push edx;
        }
    }

    int stackAdvance = (2 + count) * 4;

    _asm
    {
        mov eax, dword ptr [format];
        push eax;
        mov eax, dword ptr [file];
        push eax;

        call dword ptr [fscanf];

        mov result, eax;
        mov eax, dword ptr[stackAdvance];
        add esp, eax;
    }

    return result;
}

进一步information