简体   繁体   中英

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 ?

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.

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

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

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