What are the printf functions for C?
In general, printf () is a library function under C header file stdio.h and conio.h both. And generally, it is used for displaying an outcome of a program to outside world. Printf() function is often used to our program to do formatted output. All variants of printf function use same formatting techniques. There is a string that specifies the layouts of output is call format specifier. i.e. %s, %d, %f, %c, %x, %u etc.
This function uses first format specifier for the first argument, second format specifier for the second argument and so on. There must be enough arguments for each format specifier otherwise, the result will be unpredictable due to less argument. And excess arguments are merely ignored. Format specifier determines how and what kind of data types will print to screen. There are various format specifiers you can use, these are:
- %c ->char single character
- %d (%i) ->int signed integer
- %e (%E) ->float or double exponential format
- %f ->float or double signed decimal
- %g (%G) ->float or double use %f or %e as required
- %o ->int unsigned octal value
- %p ->pointer address stored in pointer
- %s ->array of char sequence of characters
- %u ->int unsigned decimal
- %x (%X) ->int unsigned hex value
In turbo C there are seven variants of printf function to do the different specific job. These are:
- printf() -> sends formatted output to a standard output device
- cprintf() -> sends formatted output to a text window on the screen
- sprintf() -> sends formatted output to a string (sends to an array in memory)
- fprintf() -> sends formatted output to a File stream
- vprintf() -> sends formatted output to stdin using an argument list
- vfprintf()->sends formatted output to a File using an argument list
- vsprintf()->sends formatted output to a string using an argument list
Here prefix of printf f,s,v,c stands for:
- f -> means it takes a FILE* param to write to.
- s -> means it writes to a string buffer.
- v ->means it takes all the value args as a single vector (array).
- c ->means it write to the console (Text window on the screen)
Function and its argument table by turbo C
Argument | Functions | What Argument Is/Does |
arglist | vprintf | Pointer to a list of arguments |
argument | cprintf,
fprintf, printf, sprintf |
One of a series of arguments to which the functions apply a format specifier contained in *format |
buffer | sprintf,
vsprintf |
Buffer where function writes the string |
format | (all) printf variant | Format string |
stream | fprintf,
vfprintf |
Stream where the functions output the formatted data |
More details about specifier, flags, width, precision used with printf varrient:
specifier |
Output |
Example |
---|---|---|
d or i | Signed decimal integer | 392 |
u | Unsigned decimal integer | 7235 |
o | Unsigned octal | 610 |
x | Unsigned hexadecimal integer | 7fa |
X | Unsigned hexadecimal integer (uppercase) | 7FA |
f | Decimal floating point, lowercase | 392.65 |
F | Decimal floating point, uppercase | 392.65 |
e | Scientific notation (mantissa/exponent), lowercase | 3.9265e+2 |
E | Scientific notation (mantissa/exponent), uppercase | 3.9265E+2 |
g | Use the shortest representation: %e or %f | 392.65 |
G | Use the shortest representation: %E or %F | 392.65 |
a | Hexadecimal floating point, lowercase | -0xc.90fep-2 |
A | Hexadecimal floating point, uppercase | -0XC.90FEP-2 |
c | Character | a |
s | String of characters | sample |
p | Pointer address | b8000000 |
n | Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location. |
|
% | A % followed by another % character will write a single % to the stream. | % |
The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags |
description |
---|---|
- | Left-justify within the given field width; Right justification is the default (see width sub-specifier). |
+ | Forces to preceded the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign. |
(space) | If no sign is going to be written, a blank space is inserted before the value. |
# | Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written. |
0 | Left-pads the number with zeroes (0) instead of spaces when padding is specified. |
width |
description |
---|---|
(number) | The minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. |
* | The width is not specified in the format string, but as an additional integer, value argument preceding the argument that has to be formatted. |
.precision |
description |
---|---|
.number | For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default, all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed. |
.* | The precision is not specified in the format string, but as an additional integer, value argument preceding the argument that has to be formatted. |
Now we move on each example of printf variant:
printf():
Print formatted data to stdout device. It’s writing the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
Prototype of printf:
int printf ( const char * format, ... );
parameters:
Format specifier prototype for printf function:
%[flags][width][.precision][length]specifier
Return Value:
Returns number of written character if successful otherwise, return a negative value.
Program #1
#include<stdio.h> #include<conio.h> void main() { int total=1511; //%d is use here to accpt value of total of int type// printf("The value of total is = %d",total); // Wait for a keypress // getch(); }
Output
The value of total is = 1511
program #2
#include<stdio.h> #include<conio.h> void main() { int total1=1511,total2=235, total3=12; //%4d is use here to accpt value of all total variable // printf("The value of total1 is = %d \n",total1); printf("The value of total2 is = %d \n",total2); printf("The value of total3 is = %d \n",total3); // Wait for a keypress // getch(); }
Output:
The value of total is = 1511 The value of total is = 235 The value of total is = 12
Here we change the format specifier %d to %4d, as a result, you will see the alignment will change.
program #3
#include<stdio.h> #include<conio.h> void main() { int total1=1511,total2=235, total3=12; //%4d is use here to accpt value of all total variable with 4 digit alignment// printf("The value of total1 is = %4d \n",total1); printf("The value of total2 is = %4d \n",total2); printf("The value of total3 is = %4d \n",total3); // Another format printf("The value of total1 is = %04d \n",total1); printf("The value of total2 is = %04d \n",total2); printf("The value of total3 is = %04d \n",total3); // Wait for a keypress // getch(); }
Output:
The value of total is = 1511 The value of total is = 235 The value of total is = 12
The value of total is = 1511 The value of total is = 0235 The value of total is = 0012
As we discuss earlier format specifier should be same as the argument. In this program we have 3 format specifier in respect of 4 arguments as a result the last argument is ignored. See bellow program.
program #4
#include<stdio.h> #include<conio.h> void main() { int total1=1511,total2=235, total3=12 total4=25; //Specify exact number of format specifier in respect of argument// printf("The value of total1 is = %d,\n total2 is =%d,\n total3 is =%d \n",total1,total2,total3,total5); // Wait for a keypress // getch(); }
Output:
The value of total is = 1511 The value of total is = 235 The value of total is = 12
cprintf():
Unlike printf function, cprintf take argument same as printf function. And applies to each of the format specifier contained in the format string, pointed to by format, and prints the formatted data directly to the current text window on the screen. The number of available format must match the number of arguments. Depending _directvideo of the global variable, the string is written either directly or through a BIOS call to screen memory. By using window framing and coloring you can make your program output more attractive user interface uusing cprintf.
Prototype of cprintf:
int cprintf(const char *format[, argument, ...]);
parameters:
Format specifier prototype for cprintf function:
%[flags][width][.precision][length]specifier
Return Value:
Returns number of written character if successful otherwise, return a negative value.
program #5
#include <conio.h> int main(void) { /* clear the screen */ clrscr(); /* create a text window */ window(10, 10, 80, 25); /* output some text in the window */ cprintf("Hello TechNHIT\r\n"); /* wait for a key */ getch(); return 0; }
program #6
#include <conio.h> int main(void) { window(10,10,40,11); textcolor(RED); textbackground(WHITE); cprintf("This is a test Program\r\n"); getch(); return 0; }
program #7
#include<stdio.h> #include<conio.h> main() { window(10,10,40,11); textcolor(YELLOW+BLINK); cprintf("Hello TechNhit"); getch(); return 0; }
Output:
sprintf():
It composes a string to an array(buffer) rather than print to screen or any stdout. It supports all format same as printf. A terminating null character is automatically appended after the content.
Sometimes we need a complete string with a changeable section for example if you send a hello string to your individual user. It is more convenient way to write a pattern using user variable rather than write to individual one. Hence sprintf is the most selective function for this kind of job.
Prototype of sprintf:
int sprintf ( char * str, const char * format, ... );
parameters:
*str ->Pointer to an array (buffer) where the resulting C-string is stored.
The buffer should be large enough to contain the resulting string.
Format specifier prototype for sprintf function:
%[flags][width][.precision][length]specifier
Return Value:
Returns number of written character if successful otherwise, return a negative value. Note that character counts do not include the additional null-character automatically appended at the end of the string.
program #8
#include <stdio.h> int main(void) { char buffer[80]; //here we declare some variable with value char user[10]={"Mondal"}; clrscr(); // sprintf dose not print to screen its sets formatted output to an array sprintf(buffer, "Hey Hello %s\n", user); // prints an array to screen puts(buffer); strcpy(user,"Paul"); sprintf(buffer, "Hey Hello %s\n", user); puts(buffer); strcpy(user,"Bannerjee"); sprintf(buffer, "Hey Hello %s\n", user); puts(buffer); getch(); return 0; }
Output:
fprintf():
This function writes formatted data to a file stream. fprintf uses all format specifier as its argument, unlike printf function.
Prototype of fprintf:
int fprintf ( FILE * stream, const char * format, ... );
parameters:
*stream ->Pointer to a FILE object that identifies an output stream.
Format specifier prototype for fprintf function:
%[flags][width][.precision][length]specifier
Return Value:
Returns number of written character if successful otherwise, return a negative value.
program #9
#include <stdio.h> int main(void) { FILE *stream; int i = 100; char c = 'C'; float f = 1.234; /* open a file for update w+ (Write Mode) */ stream = fopen("DUMMY.FIL", "w+"); /* write some data to the file */ fprintf(stream, "%d %c %f", i, c, f); /* close the file */ fclose(stream); return 0; }
If you are working with the file then you have to need the fprintf function for file operation. On above program, a file stream opens dummy file as write mode then fprintf writes variable values to file stream. If you haven’t set any path for the file then it created in the present directory where the program runs from.
vprintf():
Print formatted data from variable argument list to stdout. It writes the C string pointed by format to the standard output (stdout), replacing any format specifier in the same way as printf does, but using the elements in the variable argument list identified by arg instead of additional function arguments.
Internally, the function retrieves arguments from the list identified by arg as if va_arg was used on it, and thus the state of arg is likely altered by the call.
In any case, arg should have been initialized by va_start at some point before the call, and it is expected to be released by va_end at some point after the call.
Prototype of vprintf:
int vprintf ( const char * format, va_list arg );
parameters:
Format specifier prototype for vprintf function:
%[flags][width][.precision][length]specifier
arg -> A value identifying a variable arguments list initialized with va_start.
va_list is a special type defined in <cstdarg>.
Return Value:
After successful, it will return the total number of written character. And on failure, it returns a negative value.
/* vprintf example */ #include <stdio.h> #include <stdarg.h> void WriteFormattedOutput ( const char * format, ... ) { va_list args; va_start (args, format); vprintf (format, args); va_end (args); } int main () { WriteFormattedOutput ("Call with %d variable argument.\n",1); WriteFormattedOutput ("Call with %d variable %s.\n",2,"arguments"); return 0; }
Output:
Call with 1 variable argument.
Call with 2 variable arguments.
vsprintf():
Write formatted data from variable argument list to a string. Composes a string with the same text that would be printed if the format was used on printf, but using the elements in the variable argument list identified by arg instead of additional function arguments and storing the resulting content as a C string in the buffer pointed by s.
Internally, the function retrieves arguments from the list identified by arg as if va_arg was used on it, and thus the state of arg is likely to be altered by the call.
In any case, arg should have been initialized by va_start at some point before the call, and it is expected to be released by va_end at some point after the call.
Prototype of vprintf:
int vsprintf (char * str, const char * format, va_list arg );
parameters:
*str ->Pointer to an array (buffer) where the resulting C-string is stored.
The buffer should be large enough to contain the resulting string.
Format specifier prototype for vsprintf function:
%[flags][width][.precision][length]specifier
arg -> A value identifying a variable arguments list initialized with va_start.
va_list is a special type defined in <cstdarg>.
Return Value:
Returns number of written character if successful otherwise, return a negative value.
#include <stdio.h> #include <stdarg.h> void PrintFError ( const char * format, ... ) { char buffer[256]; va_list args; va_start (args, format); vsprintf (buffer,format, args); perror (buffer); va_end (args); } int main () { FILE * pFile; char szFileName[]="myfile.txt"; pFile = fopen (szFileName,"r"); if (pFile == NULL) PrintFError ("Error opening '%s'",szFileName); else { fclose (pFile); } return 0; }
In this example, if the file myfile.txt does not exist, prior is called to show an error message similar to:
Error opening file ‘myfile.txt’: No such file or directory
Subroto Mondal
Latest posts by Subroto Mondal (see all)
- Installing and Configuring OpenShift: A Step-by-Step Guide for Linux Experts with Terminal Code - February 19, 2023
- Sed Command in Linux with Practical Examples - February 19, 2023
- Rsync Command uses with examples - February 19, 2023