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

梦想的初衷 提交于 2019-12-02 01:20:19

No.

Your code will cause a run-time exception. You can use /dev/null for example, if you're running on an OS that supports it, but there's nothing like that built-in in C++.

To solve your actual problem (stated in comments), use snprintf instead of printf, provided that it's available in your C++ implementation (which is not guaranteed in C++03). Pass in a null pointer for the buffer and 0 for the size. Nothing is written, but the return value is the length of the formatted string (excluding nul terminator).

[Edit: oops, I forgot that snprintf on Windows doesn't conform to C99. It returns an error if truncation occurs, not the required length. I don't know what they're going to do about the fact that C++0x requires C99-conforming snprintf.]

To answer your question, you can fopen /dev/null on UNIX-like systems or nul on Windows. Writes to the resulting FILE* have no effect. However, there is no portable null-device.

why not wrapping the fprintf method call with an if (NULL != nothing) statement?

Although as NirMH said, you can enclose it in if (nothing != NULL), there is another way. You can open a file in read mode (with "r") and when you send it to fprintf, the write is ignored (Edit: as discussed in the comments, remember to set n=0 if it was negative as returned by fprintf).

I personally suggest the first method though. The only reason I might do the second is if I can't change the function.

If you don't care if your code is system dependent, you can use /dev/null in linux, nul in windows etc,

Offirmo

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.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!