layzak layzak -5 years ago 232
Linux Question

How to implement a printing function?

Most of the time, when I need a specific functionality not implemented in the standard library, I try to implement it myself. I also create static libraries to use and reuse code.

So I was thinking of writing a test program independent from standard library. This program is missing a printing function. Printing, usually,is a major part of a computer program.

How can a printing function as simple as

be implemented in C or C++?

My Code:

#define TRUE 1
#define FALSE 0

typedef int INT_32;
typedef unsigned int size_t;

struct block {
INT_32 v;
size_t x;

void f1(struct block *s);
int f2(void *addr);

int main(void)
struct block blk;
//print blk members

int res = f2(&blk);
// print res

return 0;

void f1(struct block *s)
s->v = -1;
s->x = 1

int f2(void *addr)
if (addr) {
return TRUE;
else {
return FALSE;

Answer Source

Well, the most basic one I can come up, for POSIX systems, is:

void putchar(int ch)
  const unsigned char character = (unsigned char) ch;
  write(STDOUT_FILENO, &character, 1);

This just asks the write() system call to do the write, to stdout. On non-POSIX systems you're going to have to use something else.

The int-format character is knocked down to an unsigned character to comply with the specification for putchar(). I removed bitwise-AND I had there since it hardcodes 8-bit bytes which is ugly and pointless. This should be fine and keep the proper bits.

You're going to have to use system calls, there's no "native" printing in C after all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download