Hacker News new | ask | show | jobs
by joosters 1562 days ago
Since the article is being pedantic, here's another pedantic complaint: What if printf() can't write all of its output, but manages to write some of it? printf() returns the number of bytes written, but (and I'm sure someone will correct me if I'm wrong!) it doesn't guarantee to be atomic - it can't either write everything or nothing. Imagine a complicated printf() call with lots of parameters and long strings - some of it might get written, then the next write() that it does fails due to lack of space. What does printf() do then?

The article cites an example of writing a YAML file and the dangers of it being half-written. Well, you could imagine outputting a file all in one printf() with lots of %s's in the format string. Some get written, but not all. If printf() decides to return an error message, retrying the printf() later on (after deleting another file, say), will corrupt the data because you'll be duplicating some of the output. But if printf() just returned the number of bytes written, your program will silently miss the error.

So does 'Hello World\n' need to check that printf() succeeded, or does it actually need to go further and check that printf() returned 12? (or is it 13, for \r\n ?) I don't think there's any way to really safely use the function in real life.

2 comments

If printf can write some bytes but not all of them. The C documentation is explicit:

> a negative value if an output error occurred

So in your case that's an error and printf returns a negative value. But yes, how many bytes were written is a lost information.

> So does 'Hello World\n' need to check that printf() succeeded, or does it actually need to go further and check that printf() returned 12?

No. According to fprintf(1), when the call succeeds it returns the number of printed characters. If it fails (for example, if it could only print part of the string) then it returns a negative value.

The number of printed characters is useful to know how much space was used on the output file, not to check for success. Success is indicated by a non-negative return value.