Formatted output aur format contracts
Output conversions ko types se match, width/precision distinguish aur bounded formatting/stream failures check karein.
Is chapter mein7 sections
Formatted output data ko display instructions ke saath jodta hai. Format string aur supplied argument types ka match hona chahiye. Is agreement ko carefully padhkar storage limits aur output failures handle karenge.
1. Format argument contract specify karta hai
printf stdout par, fprintf chosen stream par aur snprintf bounded character array mein write karta hai. Format string mein ordinary text aur % se starting conversions hoti hain. Unki requirements call ki correctness ka part hain. %% percent sign print karta hai bina value argument consume kiye.
| Output conversion | Required value |
|---|---|
%d, %i | int, decimal |
%u, %x | unsigned int, decimal / hexadecimal |
%ld, %lld | long / long long |
%zu | size_t |
%f, %e, %g | double; float promote hokar double banta hai |
%Lf | long double |
%c | Required promotions ke baad int |
%s | Readable character sequence; normally null terminated |
%p | void *; appropriate object-pointer cast use karein |
Variadic calls default argument promotions apply karti hain: float double banta hai aur eligible small integer types integer promotion undergo karte hain. %d se size_t format infer nahi hota. Matching format ya explicitly justified value conversion use karein. <inttypes.h> ke PRI macros available corresponding integer typedefs ke formats dete hain. Pointer formatting implementation-defined hai aur function pointers portably print nahi karta.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int score = 73;
size_t count = 3;
float ratio = 0.5f;
int written = printf("score=%d count=%zu ratio=%.1f\n", score, count, ratio);
if (written < 0) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
2. Width aur precision presentation control karti hain
%8d jaisi width minimum field width request karti hai; larger result eight characters mein truncate nahi hota. Precision ka meaning conversion-specific hai: %.2f two fractional digits, %.4d minimum integer digits aur %.3s character sequence se printed bytes limit karta hai. * width/precision int argument consume karti hai. Output rules scanf ki input field width se interchangeable nahi.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char label[3] = { 'C', 'A', 'T' };
if (printf("%.3s\n", label) < 0) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
Three-element array mein terminating null character nahi. Yeh particular precision conversion ko three valid elements ke andar rakhti hai. Plain %s ko accessible storage mein terminating null character chahiye. Runtime lengths ke liye int precision mein length representable hai check karke convert karein; negative precision omitted treat hoti hai, zero-length safety bound nahi.
3. External data ko format language se alag rakhein
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *message = "progress: 100%";
if (printf("%s\n", message) < 0) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
Fixed "%s\n" format hai; message data hai. External text ko printf(message) pass karne se percent sequences conversion instructions ban sakti hain, missing arguments ya %n ke through writes ke saath. Plain text ke liye fixed format ya fputs use karein. %s value ke roop mein passed string ka percent sign escape karna required nahi.
4. Bounded output ka result bhi check karein
char label[5];
int needed = snprintf(label, sizeof label, "%s", "Codedile");
bool failed = needed < 0;
bool truncated = !failed && (size_t)needed >= sizeof label;
Fragment <stdio.h> aur <stdbool.h> use karta hai. Positive capacity par snprintf at most capacity minus one characters write karke result terminate karta hai. Nonnegative return sufficient space hoti toh kitne characters write hote, uska count hai, terminator excluded. Pehle negative error result handle karein; phir size_t convert karke capacity compare karein. Capacity ya greater value truncation hai, chahe stored prefix terminated ho.
Source/destination ke pointer aur overlap contracts phir bhi apply karte hain; snprintf overlapping strings copy karne ki permission nahi. Successful formatting call buffered stream output durable bhi nahi banati. printf/fprintf output ya encoding error par negative result report karte hain; later fflush ya fclose par bhi failure aa sakti hai.
Primary references aur aage ki reading
- WG14 N1570 — public C11 committee draft: 6.5.2.2, 7.8.1, 7.21.6.1, 7.21.6.3, 7.21.6.5. C17 baseline ke stable core provisions ke liye; final ISO publication nahi.
- WG14 N3096 — public C23 working draft: 7.23.6.1. C23 notes C17 example checks se separately source-reviewed hain.
Later variadic-functions chapter samjhata hai ki format string ke peeche argument types ka explicit agreement kyun chahiye.
Aage badhne se pehle
- Formats supplied argument types aur relevant promotions se match hone chahiye.
- Width, precision aur destination capacity different formatting questions hain.
- Output errors aur truncation ko chosen function ke rules se check karna hai.
In ideas ko alag rakhein
- Bounded output / Complete output
- Capacity-limited write fail ya truncate ho sakti hai; return result se provided output ka pata chalta hai.
snprintf ke baad buffer ko complete requested message maanne se pehle kya check karenge?
Optional: bolkar samjhein ya note rakhein. Tayyar hon toh aage badh sakte hain.Apni understanding check karein
Optional hai. Answers save ya send nahi hote; chapter kabhi lock nahi hota.
Har choice ki explanation padhein
- Sirf output kitne characters jaisa dikhna chahiye.
Appearance se conversion ka valid argument type establish nahi hota.
- Sirf variable ke naam se.
Identifier spelling argument ka required type nahi batati.
- Applicable argument promotions ke baad actual argument type se.
✓ Sahi reasoning. Format string contract hai; woh mismatched argument ko generally required type mein convert nahi karti.
C17
Earlier edition ka quick reference
Existing section links aur saved passages ke liye retained. Connected ideas expanded lessons mein hain; exact corrections source review mein recorded hain.
Standard Streams
Hosted C program mein stdin, stdout aur stderr pehle se open hote hain. Initially stderr fully buffered nahi hota; commonly unbuffered hai, lekin standard exactly wahi mode require nahi karta. Interactive standard input/output commonly line-buffered hota hai; buffering stream aur environment par depend karti hai.
Formatted I/O
printf aur scanf — aur inke file-oriented siblings fprintf/fscanf — ek format string use karte hain jisme conversion specifiers hote hain:
| Specifier | printf / fprintf argument | scanf / fscanf destination |
|---|---|---|
| %d | int, decimal output | int *, decimal input |
| %i | int, decimal output | int *, base-detecting input (C17 mein decimal/octal/hex) |
| %u | unsigned int, decimal output | unsigned int *, unsigned decimal conversion |
| %f / %e | double (float promote hokar double banta hai) | float * |
| %lf / %le | double; l se yeh output conversions nahi badalti | double * |
| %Lf / %Le | long double | long double * |
| %c | Integer promotions ke baad int, character ki tarah print | char *; null terminator nahi, leading whitespace skip nahi |
| %s | Null-terminated character string ka pointer | Enough space wala char array; field width use karein |
| %x / %X | unsigned int, hexadecimal output | unsigned int *, hexadecimal input |
| %p | void *; jaise printf("%p", (void *)p) | void **; implementation-defined pointer text |
| %% | Literal percent print; argument nahi | Literal percent match; destination nahi |
Length modifiers actual types se match hone chahiye: output mein %ld ko long, input mein long *; %zu ko respectively size_t aur size_t * chahiye. char word[20] ke liye scanf("%19s", word) terminating null character ki space rakhta hai; result use karne se pehle return value 1 check karein. Doosri input calls ka expected assignment count bhi check karein. Robust numeric input ke liye fgets aur phir strtol jaise conversion use karein; end pointer, ERANGE aur destination type ki range check karein. Out-of-range scanf numeric conversion undefined behavior hai, sirf failed match nahi. Output bhi fail ho sakta hai; negative printf return error batata hai.
Buffering
Buffered output turant appear hona required nahi. Line-buffered output commonly newline par flush hota hai; fully buffered output buffer bharne ya flush hone tak collect hota hai. Input se pehle prompt bhejna ho toh fflush(stdout) use karein; important output ke errors check karein. Normal exit open output streams flush karta hai, abnormal termination zaroori nahi. Portable C mein fflush(stdin) input-clear operation nahi; input stream par fflush undefined behavior hai.
Character aur Line I/O
getchar ka return int hai: ya int mein converted unsigned char value, ya EOF. Isko int mein rakhein aur character mein convert karne se pehle EOF test karein; end-of-file/input error ko feof/ferror se distinguish karein. n > 1 par fgets(s, n, stream) maximum n - 1 characters read karta hai, read hui newline retain karta hai aur success par null character lagata hai. Destination mein n characters ki space rakhein aur return value check karein. Success complete line ya input mein null characters na hone ki guarantee nahi. puts newline add karta hai, fputs nahi. gets C11 mein remove hua.
Agla idea padhne ke liye tayyar?
Mark this chapter as read whenever you feel ready.