Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 14 May 2020 22:09:04 +0200
From:      Polytropon <freebsd@edvax.de>
To:        FreeBSD Questions <freebsd-questions@freebsd.org>
Subject:   Multi-line text output via printf() et al.
Message-ID:  <20200514220904.7a4c1e28.freebsd@edvax.de>

next in thread | raw e-mail | index | archive | help
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.



-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20200514220904.7a4c1e28.freebsd>