putchar() vs printf() - Is there a difference?

user3649506 picture user3649506 · May 20, 2014 · Viewed 25k times · Source

I am currently in chapter 1.5.1 File copying and made a program like so:

#include <stdio.h>

/* copy input to output; 1st version */
main()
{
    int c;

    c = getchar();
    while (c != EOF) {
        putchar(c);
        c = getchar();
    }
}

If I ran it like this:

PS <..loc..> cc copy-0.c
PS ./a
Black
Black
White
White
Gray
Gray

The output is what I input.

And here's a program I made for experimental purposes:

#include <stdio.h>

/* copy input to output; 1st version */
main()
{
    int c;

    c = getchar();
    while (c != EOF) {
        printf("%c",c);
        c = getchar();
    }
}

It produces the same result but is there a difference between putchar and printf?

Which is better to use between the 2?

Answer

kirbyfan64sos picture kirbyfan64sos · May 20, 2014

printf is a generic printing function that works with 100 different format specifiers and prints the proper result string. putchar, well, puts a character to the screen. That also means that it's probably much faster.

Back to the question: use putchar to print a single character. Again, it's probably much faster.