简体   繁体   中英

In which cases does printf return a negative value?

I'v been working on my own version of printf for educational purposes and while reading the manual I read that the function can return negative value when facing an error.

At first I believed that it returns -1 / negative value when an error occurs in the format string but this is not the case.

I began to think that it returns -1 when it encounters some syscall error and doesn't succeed in writing to the file descriptor, then I tested this code to check this idea:

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    errno = 0;
    int stdout2 = dup(STDOUT_FILENO);
    close(STDOUT_FILENO);
    int ret = printf("Hey", "Hello");
    fprintf(stderr, "%d\t%s\n", ret, strerror(errno));
}

It outputted:

3       Bad file descriptor

Errno is set, there is actually an error (the file descriptor is close) but no negative values are outputted.

I'm on Linux and use the glibc, but I also encountered this case in MacOS. Any idea?

In which case printf return a negative value?

The C standard says (C99 draft):

The printf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred

The POSIX standard says:

If an output error was encountered, these functions shall return a negative value and set errno to indicate the error.

So i read all your comments and thanks to Peter i closed stdoud like this

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    errno = 0;
    fclose(stdout);
    int ret = printf("Hey", "Hello");
    fprintf(stderr, "%d\t%s\n", ret, strerror(errno));
}

And it finally returns -1. But i'm surprised that printf does'nt check the values of system calls and threat them as error when they are (because when i close the file descriptor directly the printf does'nt work and set errno to Bad File Descriptor but return the number of characters and not an error). Thanks for all of your answers. And sorry if i left some messy code i was just testing at 4am haha.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM