Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 14 May 2020 23:18:10 +0300
From:      Yuri Pankov <ypankov@fastmail.com>
To:        Polytropon <freebsd@edvax.de>, FreeBSD Questions <freebsd-questions@freebsd.org>
Subject:   Re: Multi-line text output via printf() et al.
Message-ID:  <0d78f2bb-4169-c1ba-48c0-3f9c6993c961@fastmail.com>
In-Reply-To: <20200514220904.7a4c1e28.freebsd@edvax.de>
References:  <20200514220904.7a4c1e28.freebsd@edvax.de>

Next in thread | Previous in thread | Raw E-Mail | Index | Archive | Help
Polytropon wrote:
> In the FreeBSD sources, there are several ways shown about
> how to emit several lines of text to the console or to a
> file. Allow me to phrase the question in C, even though
> it will be a valid question in almost every other programming
> language (compiled or interpreted):
> 
> What is the _proper_ way of printing multiple lines?
> 
> My research basically did bring up the following methods:
> 
> a) multiple function calls:
> 
> 	printf("This is the first line of text.\n");
> 	printf("And this is the second line.\n");
> 	printf("Finally a third line.\n");
> 
> b) one string in multiple parts in one function call:
> 
> 	printf("This is the first line of text.\n"
> 		"And this is the second line.\n"
> 		"Finally a third line.\n");
> 
> c) multiple lines in one string:
> 
> 	printf("This is the first line of text.\n
> 	And this is the second line.\n
> 	Finally a third line.\n");
> 
> There is a specific restriction that if a string contains
> conversion specifications for variables, those have to be
> in the 1st argument, so printf() does not print several
> strings as individual arguments except there's a first
> one containing appropriate %s entries. This applies for
> any string containing %<something>: it has to be in the
> first argument passed to printf().
> 
> d) multiple strings with format string:
> 
> 	printf("%s%s%s",
> 		"This is the first line of text.\n",
> 		"And this is the second line.\n",
> 		"Finally a third line.\n");
> 
> In this case, the \n could be in the format string instead
> of the text lines.
> 
> So, what's the correct (or at least recommended way) of
> doing this? Think about use cases like fprintf(stderr, ...)
> for things like usage messages, or printing to a file for
> multi-line entries.

b) and d) are what I see the most in the code, b) mostly in illumos 
(solaris) codebase and d) in FreeBSD codebase.  I just checked how some 
utilities print their usage messages (as that's where you'd expect 
multiline strings):

https://svnweb.freebsd.org/base/head/bin/cp/utils.c?revision=326025&view=markup#l550
https://svnweb.freebsd.org/base/head/bin/mv/mv.c?revision=326025&view=markup#l506
https://svnweb.freebsd.org/base/head/bin/ln/ln.c?revision=326025&view=markup#l352

I've also seen a); c) looks completely weird to me.



Want to link to this message? Use this URL: <http://docs.FreeBSD.org/cgi/mid.cgi?0d78f2bb-4169-c1ba-48c0-3f9c6993c961>