May printf (or fprintf or dprintf) return ("successfully") less (but non-negative) than the number of "all bytes"?

The manual says that

After a successful return, these functions [printf, dprintf, etc.] return the number of characters printed.

The manual does not indicate that this number may be less (but still non-negative) than the length of the final line (replace and format). It also does not mention how to check if the string has been (or reached) completely written.

The dprintf function works with a file descriptor. Similar to the recording function for which the manual indicated that

On success, the number of bytes written is returned (zero indicates that nothing was written). This is not an error if this number is less than the number of bytes requested;

So, if I want to write a line completely, then I have to enclose n = write()a while loop. Should I do the same with dprintf or printf?

+4
source share
4 answers

My understanding of the documentation is what dprintfwill lead to the failure or output of all output. But I agree that this is some kind of gray area (and I can misunderstand); I assume that partial inference is a kind of failure (therefore returns a negative size).

Here is the musl-libc implementation :

stdio/dprintf.c dprintf vdprintf

stdio/vdprintf.c :

static size_t wrap_write(FILE *f, const unsigned char *buf, size_t len)
{
    return __stdio_write(f, buf, len);
}

int vdprintf(int fd, const char *restrict fmt, va_list ap)
{
    FILE f = {
        .fd = fd, .lbf = EOF, .write = wrap_write,
        .buf = (void *)fmt, .buf_size = 0,
        .lock = -1
    };
    return vfprintf(&f, fmt, ap);
}

, dprintf , vfprintf ( fprintf....).

, , snprintf asprintf write (2) .

stdio/__stdio_write.c __stdio_write ( writev (2) ).

, ; , , (, HTTP-), (, snprintf / asprintf), write (2).

PS. C, dprintf; GNU glibc libio/iovdprintf.c

+2

stdio, , stdio ( ) , .

stdio , , , , - , , .

d- , POSIX , stdio .

, .

+1

printf(), .

printf , . C11dr ยง7.21.6.3 3

, . 0 . .

, , stdout.

stdout , , printf(). printf() fflush(stdout)

int r1 = printf(....);
int r2 = fflush(stdout);
if (r1 < 0 || r2 != 0) Handle_Failure();

"" putchar() .

+1

My bet is that no . (After viewing - obfuscation - the source of printf.) Thus, any non-negative return value means that printf was completely successful (reached the end of the format line, everything was transferred to the kernel buffers).
But some (authentic) people need to confirm this.

0
source

Source: https://habr.com/ru/post/1661084/


All Articles