YOUR C LEARNING COMPANION

Kahan se padhein?

Learning path
Input ke saath kaamChapter 52 of 73

Lines, boundaries aur checked parsing

Input acquisition, complete-record boundaries, text conversion aur application validation separate karein.

7 min readIntermediateC17 baseline
Offline reading
Is chapter mein7 sections
0% through this chapter

Text padhna aur valid value accept karna alag jobs hain. Pehle decide karein ki ek complete input record ke bytes kaun-se hain. Phir parse karke allowed range check karein. Yeh steps alag rakhne se rejected input handle karna clear hota hai.

1. Fgets chunk deta hai, complete-record guarantee nahi

Complete C17 program
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char chunk[8];
    if (fgets(chunk, sizeof chunk, stdin) == NULL) {
        if (ferror(stdin)) return EXIT_FAILURE;
        return EXIT_SUCCESS;
    }
    if (fputs(chunk, stdout) == EOF) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

Eight ki positive capacity par fgets at most seven characters read karke success par null terminator add karta hai. Read hui newline retain hoti hai. 12345678 aur newline input mein first chunk sirf 1234567 hai; eighth character aur newline unread hain. Example deliberately embedded NUL ke bina input ka first-chunk demonstration hai.

Successful chunk mein newline absent ho toh final unterminated line, exactly filled available space ya overlong record ka remainder ho sakta hai. Simple no-newline-means-too-long test incomplete hai. Read failure valid empty string bhi nahi: any character se pehle EOF par fgets array unchanged chhodta hai; read error par contents indeterminate hain. Buffer sirf success ke baad use karein.

2. Record aur length contract explicitly choose karein

Next reader newline se pehle at most seven C bytes accept, line separator remove aur nonempty final line bina newline accept karta hai. Empty line aur immediate EOF distinct hain. NUL wali line reject hoti hai kyunki next stage null-terminated strings use karti hai. Rejection par bhi separator ya EOF tak consume hota hai, taaki next request next record se start ho.

Chaar separate questions
Acquire
Reading succeed hui?
Frame
Complete record limit mein tha?
Convert
Text value represent karta hai?
Validate
Yeh value yahan allowed hai?
Har required stage succeed hone se pehle application state update na karein.
Complete bounded-line example padhein
Complete C17 program
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

enum LineResult { LINE_OK, LINE_END, LINE_TOO_LONG, LINE_NUL, LINE_ERROR };

/* capacity >= 1; buffer has capacity writable characters; stream is readable. */
static enum LineResult read_line(FILE *stream, char *buffer, size_t capacity)
{
    size_t used = 0;
    bool saw_data = false, too_long = false, has_nul = false;
    int ch;
    while ((ch = fgetc(stream)) != EOF && ch != '\n') {
        saw_data = true;
        if (ch == '\0') { has_nul = true; continue; }
        if (used < capacity - 1) ((unsigned char *)buffer)[used++] = (unsigned char)ch;
        else too_long = true;
    }
    buffer[used] = '\0';
    if (ch == EOF && ferror(stream)) return LINE_ERROR;
    if (ch == EOF && !saw_data) return LINE_END;
    if (has_nul) return LINE_NUL;
    if (too_long) return LINE_TOO_LONG;
    return LINE_OK;
}

int main(void)
{
    char line[8];
    for (;;) {
        enum LineResult result = read_line(stdin, line, sizeof line);
        if (result == LINE_END) break;
        if (result == LINE_ERROR) return EXIT_FAILURE;
        if (result == LINE_TOO_LONG) {
            if (puts("too long") == EOF) return EXIT_FAILURE;
        } else if (result == LINE_NUL) {
            if (puts("NUL rejected") == EOF) return EXIT_FAILURE;
        } else {
            if (printf("line=[%s]\n", line) < 0) return EXIT_FAILURE;
        }
    }
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

Helper ko live readable byte-oriented stream, at least one writable buffer element aur actual capacity chahiye. EOF/newline checks tak int result rakhta hai, possibly narrower plain-char conversion ke bajay unsigned-char view se byte representation store, terminator ki room preserve aur full hone par storage stop karke record drain karta hai. Line contents use karne se pehle status check karein: rejected line ka stored prefix accepted input nahi. I/O error doosri classifications se priority rakhta hai.

Capacity C bytes count karti hai, Unicode code points ya user-perceived characters nahi. Reader text encoding validate nahi karta. Approach string build karne se pehle input NUL detect karti hai. Embedded NUL ke baad fgets ne kitne characters consume kiye, later strlen nahi bata sakta; successful fgets alone NUL-free text contract establish nahi karta. Huge records drain karne ko application/platform ki byte/time limit jaisi resource policy chahiye ho sakti hai. Helper bounded-storage teaching design hai, universal network protocol parser nahi.

3. Text convert karke application range enforce karein

Complete C17 program
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

static bool parse_score(const char *text, int *result)
{
    if (text == NULL || result == NULL) return false;
    char *end = NULL;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (end == text || errno == ERANGE) return false;
    while (isspace((unsigned char)*end)) ++end;
    if (*end != '\0' || value < 0 || value > 100) return false;
    *result = (int)value;
    return true;
}

int main(int argc, char *argv[])
{
    int score = 0;
    if (argc != 2 || !parse_score(argv[1], &score)) return EXIT_FAILURE;
    if (printf("score=%d\n", score) < 0) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

Parser optional surrounding whitespace aur sign ke saath decimal zero se hundred accept karta hai. Command-line wrapper conversion independently inspect karne deta hai; same helper bounded reader ki LINE_OK string receive kar sakta hai. End-pointer equality no conversion, ERANGE unrepresentable long result aur trailing scan chosen whitespace policy ke bahar text reject karta hai.

Isspace argument unsigned char ke through convert hota hai. Application range har standard int mein fit hai, isliye final cast representability proof ke baad hai. Failure result object unchanged chhodti hai. Policy earlier command-line example se deliberately different hai jo trailing whitespace reject karta tha; policy choose karna input contract design ka part hai.

4. Valid record ke baad state publish karein

Reading, conversion aur domain checks previously accepted score corrupt kiye bina different failures report kar sakti hain. Candidate temporary object mein rakhein aur har check succeed hone par module ka validated setter call karein. Empty record, clean EOF, invalid number, overlong line, embedded NUL aur I/O error different outcomes hain; interface decide kare ki retry, normal input end ya failure termination kya hoga.

Primary references aur aage ki reading

Aage badhne se pehle

  • Complete input record aur input call ke returned chunks alag hain.
  • Parsing mein valid data, incomplete input, invalid text aur out-of-range values alag karein.
  • Required checks successful hone ke baad accepted value commit karein.
In ideas ko alag rakhein
Buffer full / Record complete
Full read buffer mein logical line ka sirf part ho sakta hai; boundary policy remaining input decide karti hai.
Apne words mein samjhaayein

Overlong line reject karke next input record ko read ke liye ready kaise rakhenge?

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.

fgets successful ho to kya usne poori input line consume ki hi hogi?
Har choice ki explanation padhein
  1. Haan, terminating null prove karta hai ki poori line fit hui.

    Null termination prove nahi karti ki newline ya poori logical line consume hui.

  2. Haan, buffer size automatically grow hota hai.

    fgets supplied buffer dynamically enlarge nahi karta.

  3. Nahi. Line end hone se pehle buffer fill ho sakta hai.

    ✓ Sahi reasoning. Input policy ke according incomplete lines detect aur handle karein.

C17

Agla idea padhne ke liye tayyar?

Mark this chapter as read whenever you feel ready.

CHAPTER 52 / 73

Is chapter mein

Lines, boundaries aur checked parsing

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping