473,748 Members | 8,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Write a customized printf function in C

During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.

void printf (const char* format, ...);

The format can contain the following format specifiers:

format specifier := %[flags][width][.precision][modifier]type

where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }

The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.
Can any good C programmer give me a good answer? thanks!
richard
Nov 14 '05 #1
7 2553
sunfiresg wrote:
During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.

void printf (const char* format, ...);

The format can contain the following format specifiers:

format specifier := %[flags][width][.precision][modifier]type

where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }

The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.
Can any good C programmer give me a good answer? thanks!
richard


Use variable arguments facility to handle the args.
Rest should be fairly easy.
--
Karthik.
' Remove _nospamplz from my email to mail me. '
Nov 14 '05 #2
Quoth sunfiresg on or about 2004-11-14:
Write a customized printf function in C


The GNU manpage for stdarg gives the following example:

The function foo takes a string of format characters and prints
out the argument associated with each format character based on the
type.

#include <stdio.h>
#include <stdarg.h>

void foo(char *fmt, ...) {
va_list ap;
int d;
char c, *p, *s;

va_start(ap, fmt);
while (*fmt)
switch(*fmt++) {
case 's': /* string */
s = va_arg(ap, char *);
printf("string %s\n", s);
break;
case 'd': /* int */
d = va_arg(ap, int);
printf("int %d\n", d);
break;
case 'c': /* char */
/* need a cast here since va_arg only
takes fully promoted types */
c = (char) va_arg(ap, int);
printf("char %c\n", c);
break;
}
va_end(ap);
}

-trent
Nov 14 '05 #3
su*******@gmail .com (sunfiresg) wrote in message news:<62******* *************** ****@posting.go ogle.com>...
During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.

void printf (const char* format, ...);

The format can contain the following format specifiers:

format specifier := %[flags][width][.precision][modifier]type

where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }

The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.
Can any good C programmer give me a good answer? thanks!


Yes.
Nov 14 '05 #4
sunfiresg wrote:

During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.

void printf (const char* format, ...);

The format can contain the following format specifiers:

format specifier := %[flags][width][.precision][modifier]type

where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }

The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.

Can any good C programmer give me a good answer? thanks!


I posted a min_printf here once or twice:
http://groups.google.com/groups?selm...mindspring.com

It doesn't have support for any of
[flags][width][.precision][modifier]

--
pete
Nov 14 '05 #5


sunfiresg wrote:
During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.

void printf (const char* format, ...);

The format can contain the following format specifiers:

format specifier := %[flags][width][.precision][modifier]type

where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }

The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.

Can any good C programmer give me a good answer? thanks!

richard


I took this code from net long back. It does not carry the author name and
I did not test the code.
=============== =============== =untested code
starts========= =============== ==
/* printf.c */
extern putchar();

printf(fmt,firs tparm)
char *fmt;
{
return uformat(putchar ,fmt,&firstparm );
}

/* uformat - K&R C standard output formatting */

/************ Valid conversion specifications:

% {-} {nnn} {.} {mmm} {l} {d,o,x,u,c,s,e, f,g}

- = left-justify instead of right-justify
nnn = field width (0 start means pad with '0' instead of spaces)
mmm = precision (maximum # chars or # of digits to right of '.')
(default precision = 6)
l = long, not int.
d = decimal (int or long int)
o = unsigned octal (no leading zero)
x = unsigned hex (no leading 0x)
u = unsigned decimal (int or long int)
c = single character
s = string
e = [-]x.yyyyyyE[+/-]ee where precison = # y's
f = [-]xxx.yyyyyy where precision = # y's
(if precision==0, no decimal point is printed)
g = use %e or %f, whichever is shorter. (%f if equal)

*************** *************** ***************/
extern char *ultoa(),*ltoa( ),*ecvt(),*fcvt ();

int uformat( put, fmt, args )
/** Returns # of characters printed **/
int (*put)(), *args; char *fmt;
{
unsigned char c,left_justify, left_zpad,long_ prefix,
conv[33],*p,*expp,expsi gn,*s;
double dblval; long int lival;
int dec,point,sign, pad1,pad2,pad3, pad4,cnt1,cnt2, explen,
retval,width,ex cess,pad,precis ion,exp,radix;

retval = 0;
while(c=*fmt++)
{
if(c!='%' || *fmt=='%')
{
if(c=='%') fmt++;
(*put)(c);
retval++;
}
else /* c==%, not %% */
{
pad1=pad2=pad3= pad4=sign=point =explen=cnt1=cn t2=0;
radix = 16; excess = 0; precision = -3;
if(left_justify = (*fmt=='-')) fmt++;
left_zpad = (*fmt=='0');
if((width = nextnum(&fmt)) < 0) width = 0;
if(*fmt == '.')
{fmt++; precision = nextnum(&fmt);}
if(long_prefix = (*fmt=='l')) fmt++;

switch(c=*fmt++ )
{
case 'e': precision++;
case 'g':
case 'f':
dblval = *((double*)args )++;
if(precision<0) precision += 9; /* 6 or 7 */
if(c=='f')
p = fcvt(dblval, precision, &dec, &sign);
else
{
p = ecvt(dblval, precision, &dec, &sign);
exp = dec-1;
if(exp<0)
{exp = -exp; expsign = '-';}
else
expsign = '+';
conv[0] = '0';
ultoa( (long)exp, conv+1, 10);
expp = (conv[2]=='\0') ? conv : conv+1;
explen = strlen(expp)+2;
}
if(sign) sign = 1;
if(c=='g')
{
if(dec>=-3 && dec<=precision+ 5)
explen = 0;
s = p+strlen(p);
if(s!=p) while(--s!=p) if(*s=='0') *s='\0';
}
cnt1 = 1;
if(!explen)
{
if(dec<=0)
{
pad2 = 1;
pad3 = -dec;
}
cnt1 = (dec>0)? dec : 0;
}
cnt2 = strlen(p) - cnt1;
if(pad3+cnt2) point = 1;
pad = width - sign - pad2
- cnt1 - point - pad3
- cnt2 - explen;
if(pad<0)
{
pad = 0;
excess = -pad;
}
if(left_justify )
pad4 = pad;
else
pad1 = pad;
retval += width + excess;
break;

case 'd':
case 'o': radix -= 2; /* 8 */
case 'u': radix -= 6; /* 10 */
case 'x': /* 16 */

if(c=='d')
{
lival = long_prefix ? *((long*)args)+ + : *args++;
p = ltoa( lival,conv,10 ); /* signed conversion */
}
else
{
lival = long_prefix ? *((unsigned long*)args)++ :
*((unsigned int*)args)++;
p = ultoa(lival,con v,radix); /* unsigned conversion */
}
if(precision <= 0) precision = 1;
cnt2 = strlen(p);
if(*p=='-')
{cnt2--; cnt1=1;}
if((pad3=precis ion-cnt1-cnt2) < 0) pad3 = 0;
if( (pad=width-cnt1-cnt2-pad3) < 0 )
{
excess = -pad;
pad = 0;
}
if(left_justify )
pad4 = pad;
else if(!left_zpad)
pad1 = pad;
else
pad3 += pad;
retval += width + excess;
break;

case 's': p = *((char**)args+ +);
case 'c': if(c=='c')
{
conv[1] = *args++;
conv[2] = '\0';
p = conv+1;
}
cnt1 = strlen(p);
if((precision>0 )&&(precision<c nt1)) cnt1 = precision;
if( (pad=width-cnt1) < 0 )
{excess = -pad; pad = 0;}
if(left_justify )
pad4 = pad;
else
pad1 = pad;
retval += width + excess;
break;

default: (*put)(c); retval++; break;
}

while(pad1--) (*put)(' ');
if(sign) (*put)('-');
while(pad2--) (*put)('0');
while(cnt1--) (*put)(*p++);
if(point) (*put)('.');
while(pad3--) (*put)('0');
while(cnt2--) (*put)(*p++);
if(explen--)
{
(*put)('E');
(*put)(expsign) ;
while(--explen>=0) (*put)(*expp++) ;
}
while(pad4--) (*put)(' ');
}
}
return retval;
}

static int nextnum(f)
unsigned char **f;
{
register int r; char invalid,ch;
invalid = '\1';
for(r=0; (ch=**f, ch>='0' && ch<='9'); invalid = '\0')
{r = r*10 + (ch-'0'); (*f)++;}
return invalid ? -3 : r;
}

=============== ==============u ntested code ends=========== ============


--
"Combinatio n is the heart of chess"
A.Alekhine
Mail to:
sathyashrayan25 AT yahoo DOT com
(AT = @ and DOT = .)
Nov 14 '05 #6

"sunfiresg" <su*******@gmai l.com> wrote
During an interview, I am asked to answer a question:

You should implement the subset of the printf function
compliant to the following specification.

void printf (const char* format, ...);

The format can contain the following format specifiers:

format specifier := %[flags][width][.precision][modifier]type

where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }
Can any good C programmer give me a good answer? thanks!

It's a nuisance of a job. In a real situation you would probably just call
vsprintf() to do your formatting, though I have found myself implementing
vsprintf()s in my time.

You scan the format string pushing out the input until you hit a %.
The format types don't have any aliases in the modifiers, so you can scan
the string to see what you are dealing with (you can get a brownie point by
asking what you are meant to do on bad input). Then you need to read the
fields.

If you are passed a %s your argument, via the the va_args family of
functions, is a char *, if a d it is an int, and if a c it is a char.
Strings and chars can basically be passed out. Integers have to be converted
to ascii, which you do by repeatedly taking mod 10 and dividing by ten, and
then reversing the result.

As a first pass, just ignore all the modifier fields and pass out the
straight results. This gives you 90% of the functionality.

Then you need to extend the program to take account of the various fields.
It is a lengthy job but not esepecially difficult.
Nov 14 '05 #7
On Mon, 15 Nov 2004 21:40:32 +0000, Malcolm wrote:

....
If you are passed a %s your argument, via the the va_args family of
functions, is a char *, if a d it is an int, and if a c it is a char.
But remember that in variable argument lists char arguments are promoted
to int, or in rare circumstances unsigned int.
Strings and chars can basically be passed out. Integers have to be
converted to ascii,
Converted to decimal textual form. There's no reason to assume ASCII.

which you do by repeatedly taking mod 10 and
dividing by ten, and then reversing the result.


Don't forget to add '0', which will produce a decimal digit in whatever
character set the implementation is using.

Lawrence
Nov 14 '05 #8

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

Similar topics

15
3333
by: Viviana Vc | last post by:
How can I programatically do the equivalent of the following: cacls "C:\Program Files\test" /T /G Everyone:f ? Thanks, Viv
7
1636
by: Afifov | last post by:
Hello All, I have been working on some customized linux commands. I wrote the command mycpd dir1 dir2 that is supposed to copy a directory to another. I couldnt debug it in time. But here is wat it does. It reads one directory recursively, cats the output to a file and then reads that file (temporary) and call cp for each of its tokens to dir2. If anyone needs it... check it out. The mycp method is working if u need it. I can post it. ...
18
2225
by: SSG | last post by:
How to write a object oriented program in c? give me one example....
4
5646
by: childtobe | last post by:
I want to write the time to a file. (to implement this in an other piece of code that i've writen) For some reason he gives me a C2064 error when i try to put the time into a string. As you can see in the code i CAN write it to the screen, but not to a string... Any ideas? (I'm not an expert in c++ so please keep it as simple as possible :p) thanks,
6
6293
by: ericunfuk | last post by:
printf("hello"); write(1,"hello",5); Are these two have the same effect?Only the 2nd one work for me sometimes?Are there situations that I can only use write() instead of printf()? Thanks
24
4453
by: Bill | last post by:
Hello, I'm trying to output buffer content to a file. I either get an access violation error, or crazy looking output in the file depending on which method I use to write the file. Can anyone help out a newbie? #include <stdio.h> #include <ctype.h> #include <string.h>
3
5326
by: golden | last post by:
Hello, I am going to ask a question regarding write and lseek. I will provide code at the end of this, but first some background. I am trying to identify the cause of some latency in writing to disk. My user claims that performance is much slower on SAN than on local disk. The developer provided me a C++ program that performed a write
10
5331
by: riva | last post by:
This is an interview question from: http://www.freshersworld.com/interview/technical_interview_C.htm Can You write a function similar to printf() ? I can only think using putchar() and casting for such a thing.
1
2046
by: xiao | last post by:
HI~ guys , I have a program here (Sorry it is very long about 240 lines.) It can read and write the header information successfully but it cannot write the array successfully. I guess there is something wrong with the Write2DArrayInt function there. Can any one henlp me to find it out? Thank you~ (BTW : The printf function in line 114 and 139 implys that the data is right, but after that , in the new generated file, the values are all...
1
9321
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3312
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.