Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 602
Keith Miller Avatar asked Jul 06 '26 03:07

Keith Miller


2 Answers

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.

like image 155
Seth Carnegie Avatar answered Jul 08 '26 18:07

Seth Carnegie


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

like image 27
Phonon Avatar answered Jul 08 '26 18:07

Phonon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!