Keith Miller
Keith Miller

Reputation: 1347

fprintf and the NULL terminator

I am using fprintf to append a string to a document, here is the line I have a question about:

fprintf(win, bff[i - 2] != '\n' && bff[i - 2] != '\r' ? "\nmultiscreen=1" : "multiscreen=1");

The code works, it appends multiscreen=1 to the next available line in the file.

But if I understand correctly wouldn't it NOT be adding a NULL character to the end of multiscreen=1? Does this even matter since I'm writing it to a file and the trailing NULL in a string is a C thing?

Or would it be more correct to use fputs instead of fprintf?

Upvotes: 3

Views: 6207

Answers (3)

Minion91
Minion91

Reputation: 1929

You don't need the trailing \0 if you write to a file. It is just the way C uses to delimit the string because otherwise there is no way of knowing where the string ends

Upvotes: 1

Phonon
Phonon

Reputation: 12737

You don't need the NULL in the file. It's a C convention and has nothing to do with files. You're good.

Upvotes: 1

Seth Carnegie
Seth Carnegie

Reputation: 75150

String literals automatically have a 0 as the last character in them. So you don't need to add one yourself.

The NUL terminator is only for fprintf (or whatever string function you are using) to know when to stop writing characters from the pointer; no NUL is actually ever written to the file.

And yes, I would recommend using fputs instead of fprintf since you're not using any of the formatting facilities of fprintf, unless you use pmg's suggestion in the comments to your question which does use formatting sequences.

Upvotes: 7

Related Questions