473,388 Members | 1,526 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

How does printf() works

I want to know how does printf (stdio library function) works? Does
this depand on complier (I am using gcc on Linix)

Does it uses some buffer in which it stores all what needed to be
printed and in end of program it prints that or something else.

Mar 22 '08 #1
20 6811
Dnia Sat, 22 Mar 2008 04:35:24 -0700 (PDT)
Sanchit <sa************@gmail.comnapisa³(a):
I want to know how does printf (stdio library function) works? Does
this depand on complier (I am using gcc on Linix)
Uhm. It depends on implementation (so on the library not the compiler
itself).
Does it uses some buffer in which it stores all what needed to be
printed and in end of program it prints that or something else.
You'll best just grab the glibc source and find this implementation.
--
Tomasz bla Fortuna
jid: bla(at)af.gliwice.pl
pgp: 0x90746E79 @ pgp.mit.edu
www: http://bla.thera.be

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.7 (GNU/Linux)

iD8DBQFH5PKhT6wvGJB0bnkRAucXAJ9MXo8HWUUBIAenKRAWW0 FKCHrW5ACgnzXR
2PyUKHQKgpmKh83NlFQjHKM=
=2kU+
-----END PGP SIGNATURE-----

Mar 22 '08 #2
On Sat, 22 Mar 2008 12:50:53 +0100, Tomasz bla Fortuna wrote:
Dnia Sat, 22 Mar 2008 04:35:24 -0700 (PDT) Sanchit
<sa************@gmail.comnapisał(a):
>I want to know how does printf (stdio library function) works? Does
this depand on complier (I am using gcc on Linix)
Uhm. It depends on implementation (so on the library not the compiler
itself).
It depends on both the library and the compiler. For example, the
compiler may choose to transform
(void) printf("Hello, world!\n");
into
(void) puts("Hello, world!");
which behaves the same, but works differently.
Mar 22 '08 #3
On Mar 22, 4:50 pm, Tomasz bla Fortuna <b...@thera.bewrote:
Dnia Sat, 22 Mar 2008 04:35:24 -0700 (PDT)
Sanchit <sanchitgupt...@gmail.comnapisa³(a):
I want to know how does printf (stdio library function) works? Does
this depand on complier (I am using gcc on Linix)

Uhm. It depends on implementation (so on the library not the compiler
itself).
Does it uses some buffer in which it stores all what needed to be
printed and in end of program it prints that or something else.

You'll best just grab the glibc source and find this implementation.

--
Tomasz bla Fortuna
jid: bla(at)af.gliwice.pl
pgp: 0x90746E79 @ pgp.mit.edu
www:http://bla.thera.be

signature.asc
1KDownload
I have done that already.. but there is not much description
Mar 22 '08 #4
In article <cb**********************************@e10g2000prf. googlegroups.com>,
Sanchit <sa************@gmail.comwrote:
>I want to know how does printf (stdio library function) works? Does
this depand on complier (I am using gcc on Linix)
Mostly it depends on the C library implementation. The compiler
itself may know about printf() (for example, so that it can warn about
mismatches between the format and the arguments) but it doesn't have
to.
>Does it uses some buffer in which it stores all what needed to be
printed and in end of program it prints that or something else.
printf() typically works by going through the format string, outputting
the plain characters. When it comes to a % it gets the next argument
using va_arg with a type depending on the format, and then converts it
to characters and outputs it.

The output is done by calling putc() on each character - or by some
equivalent method - and that will do the usual buffering of
characters. Usually for output to a terminal it will save up the
characters until it's got a whole line, and for output to a file it
will save them up until it's got a reasonable size block. If there
are still any characters waiting in the buffer when the program ends,
they are output then. Outputting each character individually would be
slower. You can use the function setvbuf() to control the buffering.

-- Richard

--
:wq
Mar 22 '08 #5
On Mar 22, 5:21 pm, ri*****@cogsci.ed.ac.uk (Richard Tobin) wrote:
In article <cb**********************************@e10g2000prf. googlegroups.com>,

Sanchit <sa************@gmail.comwrote:
I want to know how does printf (stdio library function) works? Does
this depand on complier (I am using gcc on Linix)

Mostly it depends on the C library implementation. The compiler
itself may know about printf() (for example, so that it can warn about
mismatches between the format and the arguments) but it doesn't have
to.
Does it uses some buffer in which it stores all what needed to be
printed and in end of program it prints that or something else.

printf() typically works by going through the format string, outputting
the plain characters. When it comes to a % it gets the next argument
using va_arg with a type depending on the format, and then converts it
to characters and outputs it.

The output is done by calling putc() on each character - or by some
equivalent method - and that will do the usual buffering of
characters. Usually for output to a terminal it will save up the
characters until it's got a whole line, and for output to a file it
will save them up until it's got a reasonable size block. If there
are still any characters waiting in the buffer when the program ends,
they are output then. Outputting each character individually would be
slower. You can use the function setvbuf() to control the buffering.

-- Richard

--
:wq
can u please tell me a source where i can read this behaviour
Mar 22 '08 #6
Richard Heathfield wrote:
Johannes Bauer said:
>Are there some weird compilers out there which
omit a warning if the return value is discarded?

No doubt - but then who's to say there isn't some weird compiler out there
that warns about useless casts?
Both have existed; I once had the joy of writing a program which was
supposed to compile without warnings on one of each ...
Mar 22 '08 #7
Sanchit wrote:
>
.... snip ...
>
can u please tell me a source where i can read this behaviour
u hasn't posted here for some years.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Mar 22 '08 #8
Johannes Bauer wrote:
>
.... snip ...
>
But the transformation from printf to puts - although I know that
gcc does it - is it legal at all, according to the standard? I
could preload some library which overrides printf() - it would
never get called if the compiler subsituted the call by a puts().
No you can't. So doing involved undefined behaviour. See the
standard. The names of standard functions are reserved.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Mar 22 '08 #9
On Mar 22, 6:37 pm, CBFalconer <cbfalco...@yahoo.comwrote:
Sanchit wrote:

... snip ...
can u please tell me a source where i can read this behaviour

u hasn't posted here for some years.

[mail]: Chuck F (cbfalconer at maineline dot net)
That piece of nastiness was totally uncalled for, as a polite response
would have the same effect. Your English isn't that much better ("So
doing...)... I believe several of the regulars have plonk()'ed you for
your mostly useless noise. I only wish I knew how to do that with
google...

On a slightly (but only a very slightly) more serious note, printf is
probably implemented as a wrapper:
int printf(char *format, ...)
{
int i;
va_list v;
va_start(v, format);
i = vfprintf(stdin, format, v);
va_end(v);
return v;
}

As for a 'real' implementation - one that actually does the work of
stepping through the format string - K&R2 has a basic version that
only recognizes %i and %s in one of the chapters. The method was
mentioned earlier, no need to repeat it.

On another note, printf() and puts() cannot be exchanged: the former
returns the number of characters printed, the latter returns "a
nonnegative value" (7.19.7.10.3).

Regarding casting the returns from printf() to void: Some of my C
texts mentioned them as needed by some C error-catchers, such as lint.
I personally find they get in the way of reading code.

While signing off, I'd like to reference something I posted in my very
first post on clc: Easter this year is not two and a half weeks later
than last year. Next year, however, it occurs on April 12, which is
almost three weeks later than this year. This is caused by the
addition of a whole month in the lunar calendar. The exact placement
of this month is obviously not the same by all, as I conclude with...

Happy Purim.
-- Marty (not such a newbie anymore, and fully capable of starting a
flame war...)
Mar 23 '08 #10
Amandil wrote:
CBFalconer <cbfalco...@yahoo.comwrote:
>Sanchit wrote:

... snip ...
>>can u please tell me a source where i can read this behaviour

u hasn't posted here for some years.

That piece of nastiness was totally uncalled for, as a polite
response would have the same effect. Your English isn't that
much better ("So doing...)... I believe several of the regulars
have plonk()'ed you for your mostly useless noise. I only wish
I knew how to do that with google...
What was impolite? What English was broken? The idea is to make
the OP (and others) realize that he is writing in incomprehensible
code and to correct his behaviour.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Mar 23 '08 #11
See i have posted in a manner which can be understood. If somewhere my
English went wrong, that doesn't stopped anyone in understanding the
problem.

And I clearly stated the question. I wrote in second line

"Does it uses some buffer in which it stores all what needed to be
printed and in end of program it prints that or something else.
"

So i really wanted to know that if printf buffers or not. And if yes
then how.
Mar 23 '08 #12
Amandil said:

<snip>
I only wish I knew how to [plonk] with google...
s/with// - i.e. stop using google, and get a real newsreader. (It's the
obvious step.)
>
On a slightly (but only a very slightly) more serious note, printf is
probably implemented as a wrapper:
int printf(char *format, ...)
{
int i;
va_list v;
va_start(v, format);
i = vfprintf(stdin, format, v);
ITYM stdout, right?
va_end(v);
return v;
}

As for a 'real' implementation - one that actually does the work of
stepping through the format string - K&R2 has a basic version that
only recognizes %i and %s in one of the chapters. The method was
mentioned earlier, no need to repeat it.

On another note, printf() and puts() cannot be exchanged: the former
returns the number of characters printed, the latter returns "a
nonnegative value" (7.19.7.10.3).
Well, that sounds easy to fix - implementations that wish to swap printf()s
of string literals with a puts() call can simply arrange that the
non-negative value puts() returns is the number of characters printed.
:-)

<snip>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Mar 23 '08 #13
On Mar 23, 2:07 am, Richard Heathfield <r...@see.sig.invalidwrote:
Amandil said:

<snip>
I only wish I knew how to [plonk] with google...

s/with// - i.e. stop using google, and get a real newsreader. (It's the
obvious step.)
I know, but thus far I've been too cheap. Maybe soon. Some good
(free?) newsreaders were mentioned recently here, I started looking in
to them.

On a slightly (but only a very slightly) more serious note, printf is
probably implemented as a wrapper:
int printf(char *format, ...)
{
int i;
va_list v;
va_start(v, format);
i = vfprintf(stdin, format, v);

ITYM stdout, right?
Of course, right as usual ;)
va_end(v);
return v;
}
As for a 'real' implementation - one that actually does the work of
stepping through the format string - K&R2 has a basic version that
only recognizes %i and %s in one of the chapters. The method was
mentioned earlier, no need to repeat it.
On another note, printf() and puts() cannot be exchanged: the former
returns the number of characters printed, the latter returns "a
nonnegative value" (7.19.7.10.3).

Well, that sounds easy to fix - implementations that wish to swap printf()s
of string literals with a puts() call can simply arrange that the
non-negative value puts() returns is the number of characters printed.
:-)
Also make sure implementations swap only printf() of string literals
that ends in a '\n', because printf() does not add newline, where as
puts() does. I think there are enough differences - and the case where
there is none is extremely specific - that the implementation should
not take one function call and replace it with another. It could,
conceivably, but I wouldn't appreciate or justify it, unless puts() is
extremely faster.

-- Marty
Mar 23 '08 #14
Amandil wrote:

<snip>
Also make sure implementations swap only printf() of string literals
that ends in a '\n', because printf() does not add newline, where as
puts() does. I think there are enough differences - and the case where
there is none is extremely specific - that the implementation should
not take one function call and replace it with another. It could,
conceivably, but I wouldn't appreciate or justify it, unless puts() is
extremely faster.
As long as the "as if" rule is followed and there is no observable
difference in behaviour, the compiler is free to do whatever it wants
with your code. Or at least, I think so.

Mar 23 '08 #15
santosh said:

<snip>
As long as the "as if" rule is followed and there is no observable
difference in behaviour, the compiler is free to do whatever it wants
with your code. Or at least, I think so.
You think correctly. The "as if" rule conquers all.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Mar 23 '08 #16
Harald van Dijk schrieb:
That was Keith Thompson, and I was trying to make it more explicit for
the readers of this group, not for the compiler. As I mentioned, I
wouldn't have used the cast in actual code.
Ah, okay, first off: sorry I swapped names (reading can be kinda hard
sometimes). With the case: now I get your point, it was kind of unclear
to me previously.
>I could preload
some library which overrides printf() - it would never get called if the
compiler subsituted the call by a puts().

If you do that, as far as the standard is concerned, the behaviour is
undefined, so there are no requirements on any particular behaviour by
any implementation.
Oh, okay.

Regards,
Johannes

--
"PS: Ein Realname wäre nett. Ich selbst nutze nur keinen, weil mich die
meisten hier bereits mit Namen kennen." -- Markus Gronotte aka Makus /
Kosst Amojan / maqqusz / Mr. G / Ferdinand Simpson / Quartillia
Rosenberg in dse <45**********************@newsspool3.arcor-online.net>
Mar 23 '08 #17
Sanchit wrote:
>
See i have posted in a manner which can be understood. If somewhere my
English went wrong, that doesn't stopped anyone in understanding the
problem.

And I clearly stated the question. I wrote in second line

"Does it uses some buffer in which it stores all what needed to be
printed and in end of program it prints that or something else.
"

So i really wanted to know that if printf buffers or not. And if yes
then how.
Good. The point is that textspeak and silly abbreviations are not
catered to here. We are quite ready to make allowances for
language barriers, but those things are pure carelessness.

printf doesn't just 'work'. It is actually an entrance point to an
interpreter, which digests the format string as the program to
execute. The only thing that counts is the end result, which is
specified in the C standard.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Mar 23 '08 #18
On Mar 22, 3:37*pm, CBFalconer <cbfalco...@yahoo.comwrote:
Sanchit wrote:

... snip ...
can u please tell me a source where i can read this behaviour

u hasn't posted here for some years. *
Whereas u hasn't posted anything of value for years, if ever.
Mar 23 '08 #19
CBFalconer wrote:
Sanchit wrote:
... snip ...

can u please tell me a source where i can read this behaviour

u hasn't posted here for some years.
According to Google, U's most recent posting was on 2007-12-04. If
you're worried about case sensitivity, 'u plz' posted here on
2007-02-22. Maybe you're thinking of "Eric Binmore u", who hasn't
posted here since 1997-04-08zs
Mar 23 '08 #20
Amandil wrote:
>
On Mar 23, 2:07 am, Richard Heathfield <r...@see.sig.invalidwrote:
Amandil said:

<snip>
I only wish I knew how to [plonk] with google...
s/with// - i.e. stop using google,
and get a real newsreader. (It's the
obvious step.)
I know, but thus far I've been too cheap. Maybe soon. Some good
(free?) newsreaders were mentioned recently here, I started looking in
to them.
>
On a slightly (but only a very slightly) more serious note,
printf is
probably implemented as a wrapper:
int printf(char *format, ...)
{
int i;
va_list v;
va_start(v, format);
i = vfprintf(stdin, format, v);
ITYM stdout, right?

Of course, right as usual ;)
va_end(v);
return v;
}
.... and you really want to return (i) instead of (v), don't you?

I have a version of min_printf in my toy library:
http://www.mindspring.com/~pfilandr/C/library/std_io.c

minprintf is in K&R.

--
pete
Mar 29 '08 #21

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Grumble | last post by:
Hello, I have the following structure: struct foo { char *format; /* format string to be used with printf() */ int nparm; /* number of %d specifiers in the format string */ /* 0 <= nparm <=...
8
by: aditya | last post by:
hi, Can anybody please tell me that how the following printf(...) statement works- main(){ int d=9; printf("%d",printf("%d")); return 0;
25
by: Joakim Hove | last post by:
Hello, I have code which makses use of variables of type size_t. The code is originally developed on a 32 bit machine, but now it is run on both a 32 bit and a 64 bit machine. In the code...
10
by: bright116 | last post by:
It's strange! I wrote such fragment: char messageBody = ""; printf("message body: %s\n", messageBody); strcat(messageBody, "Signal= "); printf("message body: %s\n", messageBody);...
6
by: alternativa | last post by:
Hi, I have problem with the following function - it was intended to ask a user for a 4-digits number: double ask_for_number (void) { char *notint; char s2; double entered_number;
4
by: amit | last post by:
Hi guys!I am trying to write a program which will segregate some selected keywords from a given file.The source code is given alongwith #include<stdio.h> #include<string.h> char...
5
by: prabu | last post by:
Hi all, I want to know, what does the value of the array in the following statement mean and How to print the content of the array SMB_Negotiate using printf? unsigned char SMB_Negotiate = ...
92
by: Heinrich Pumpernickel | last post by:
what does this warning mean ? #include <stdio.h> int main() { long l = 100; printf("l is %li\n", l * 10L);
45
by: loudking | last post by:
Hello, all I don't quite understand what does ((time_t)-1) mean when I execute "man 2 time" RETURN VALUE On success, the value of time in seconds since the Epoch is retu rned. On error,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.