Brandon_J
Brandon_J

Reputation: 195

What parameters for setvbuf perform the same action as setbuf(stdin, NULL) did?

I have the question that was asked here.

The top answer had two recommendations, and one of them (which was presented as slightly more reliable) was to use setbuf(stdin, NULL);. However, the setbuf() function is deprecated, and the replacement function is setvbuf(). I am unsure how to use the parameters for this new function in a way that replicates the old function; how do I do this?

Background: when I use getchar() in a loop, the second iteration of the loop always reads the '\n' character next, and I want to get rid of that.

Upvotes: 0

Views: 426

Answers (2)

S.S. Anne
S.S. Anne

Reputation: 15584

The manpage states this (added parameters to setbuf for ease of understanding):

The other three calls are, in effect, simply aliases for calls to setvbuf(). The setbuf(FILE *stream, char *buf) function is exactly equivalent to the call

setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);

Therefore, your call would be equivalent to:

setvbuf(stream, NULL, _IONBF, BUFSIZ);

because NULL is false.

However, a much easier way to avoid the \n in a loop with getchar is to simply do this:

int c;
while((c = getchar()) != EOF)
{
    if(c == '\n')
        continue;
    /* use c as a character */
}

I'd also like to note that setbuf isn't deprecated. As a general rule, all of the functions not beginning with an underscore in Windows that are present in POSIX and not in the ANSI C standard are "deprecated" in Microsoft's eyes. If you use the underscore-prefixed versions, though, your code won't be portable. What a rabbit hole.

Upvotes: 1

Steve Summit
Steve Summit

Reputation: 48083

In answer to your stated question, the best setvbuf equivalent of

setbuf(stdin, NULL);

should be

setvbuf(stdin, NULL, _IONBF, 0);

Contrary to the note in the documentation you linked, however, I'm not aware of setbuf being deprecated, however, and I'm not aware of any disincentives to using it.

And, as I mentioned in the comments, if the reason you want to disable buffering is as a workaround for the problem that scanf tends to leave newlines "in the buffer" thus causing problems later, I would say that disabling buffering entirely is a particularly poor way of addressing that problem.

Upvotes: 2

Related Questions