Is there a file pointer (FILE*) that points to nothing?

前端 未结 6 731
醉酒成梦
醉酒成梦 2021-01-23 03:09

For some reasons I need a file pointer (FILE*) that points to nothing. It means I can pass it to fprintf function and fprintf ignore the file pointer.

for example:

6条回答
  •  执念已碎
    2021-01-23 03:25

    You are making a design mistake.

    Obviously, what you want to know is the number of chars needed to write your number.

    You are using _*printf_ for that, which is a good idea. You just want to compute the number of chars "written", hence needed. But you don't want anything to be displayed, so you pricked fprintf instead of just printf. But fprintf doesn't work without a FILE to write in...

    Like Steve said, you should rather use snprintf(), which writes into a string in memory.

    As steve says, snprintf provided with a NULL string should work as intended except on windows. Then on windows, just provide it with an temporary string which you'll discard afterward.

    size_t computeNumCharsNeededToPrintMyStuff(double d)
    {
        size_t ret = 0;
        size_t maxBuffSize = 100; // should be plenty enough
    
        char *tmpBuff = new char[maxBuffSize ];
        ret = snprintf(tmpBuff, maxBuffSize, "PI = %f", d);
        delete[] tmpBuff;
    
        return ret;
    }
    

    Then you just call :

    n = computeNumCharsNeededToPrintMyStuff(3.14)
    

    (This func could be enhanced to compute the size needed to display anything but I'd rather keep it simple for now.)

提交回复
热议问题