How to deal with wide and narrow buffers in c?

89 Views Asked by At

According to embarcadero docs we can use different Format Specifier to output a buffer to the console in my case I have a function that reads from a stream and outputs to the console but sometimes the stream is wide other times it is narrow and I have to know before hand what kind of stream is it to use the correct format specifier %sor %S

    wchar_t res[8192]= {0};
    FILE * fd;
    if ( (fd = _wpopen(command, L"rb")) == NULL)
        return 0;

    wchar_t c;
    int i =0;
    while ( (c= fgetwc(fd)) != WEOF)
    {
        res[i] = c;
        i++;
    }
    _pclose(fd);
    wprintf(L"%s", res);

Is there a way to know before hand if I should use %sor %S if not how do I ensure that it will always output the result properly

1

There are 1 best solutions below

3
chux - Reinstate Monica On

I have to know before hand what kind of stream is it to use the correct format specifier

C lib has int fwide(FILE *stream, int mode); to set/report the orientation. Use fwide(stream, 0) to report.

The fwide function returns a value greater than zero if, after the call, the stream has wide orientation, a value less than zero if the stream has byte orientation, or zero if the stream has no orientation.