YOUR C LEARNING COMPANION

Kahan se padhein?

Learning path
Input ke saath kaamChapter 54 of 73

Block I/O, positions aur update streams

Complete elements count, partial records handle, update transitions follow aur file positions carefully interpret karein.

7 min readIntermediateC17 baseline
Offline reading
Is chapter mein8 sections

Block I/O storage aur stream ke beech elements transfer karta hai. Short transfer ka meaning samajhna padta hai, aur saved file position hamesha simple byte number nahi hota. Transfer counts, position rules aur external formats alag samjhenge.

1. Fread aur fwrite complete elements count karte hain

fread(pointer, size, count, stream) size C bytes ke count elements request karta hai. Return complete elements ka count hai, necessarily bytes nahi. Size one rakhne se return byte count banta hai aur chunk processing simpler hoti hai. fwrite ka analogous count contract hai. Functions text ya binary streams par operate kar sakte hain; use karne se stream mode secretly change nahi hota.

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

int main(void)
{
    const unsigned char source[] = { 0x43, 0x00, 0xff };
    unsigned char copy[sizeof source];
    FILE *stream = tmpfile();
    if (stream == NULL) return EXIT_FAILURE;
    int status = EXIT_FAILURE;
    if (fwrite(source, 1, sizeof source, stream) != sizeof source) goto cleanup;
    if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
    if (fread(copy, 1, sizeof copy, stream) != sizeof copy) goto cleanup;
    assert(memcmp(source, copy, sizeof source) == 0);
    status = EXIT_SUCCESS;
cleanup:
    if (fclose(stream) == EOF) status = EXIT_FAILURE;
    return status;
}

Array mein embedded zero ke saath three bytes hain. Payload count define karta hai, null terminator nahi. Tmpfile temporary binary update stream create karta hai; successful seek start par laata hai aur output-to-input transition bhi provide karta hai. Har operation next stage ke result use se pehle checked hai. Goto cleanup label later har path par owned stream close karta hai.

2. Short transfer ko interpret karein

Short transfer requested se fewer complete elements return karta hai. Input ke short result ke baad feof/ferror inspect karein; output ki incomplete required write ko failure treat karein. Unfilled elements process ya missing suffix automatically zero assume na karein. Partly read element ki value indeterminate hai; count use complete record nahi banata.

Partial-element example dekhein
Complete C17 program
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const unsigned char source[] = { 10, 20, 30 };
    unsigned char items[2][2];
    FILE *stream = tmpfile();
    if (stream == NULL) return EXIT_FAILURE;
    int status = EXIT_FAILURE;
    if (fwrite(source, 1, sizeof source, stream) != sizeof source) goto cleanup;
    if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
    size_t complete = fread(items, sizeof items[0], 2, stream);
    if (ferror(stream)) goto cleanup;
    assert(complete == 1);
    assert(items[0][0] == 10 && items[0][1] == 20);
    /* Do not interpret the incomplete second item as a complete value. */
    status = EXIT_SUCCESS;
cleanup:
    if (fclose(stream) == EOF) status = EXIT_FAILURE;
    return status;
}

Checked host par three-byte temporary payload one complete two-byte item aur next ka part supply karta hai. Sirf first item interpret hota hai. Standard binary-stream rules file ke end par implementation-defined null characters append hona allow karte hain, isliye exact physical end behavior universal file-size promise nahi. External formats aur accepted trailing data define karein; ek host ke result se infer na karein.

3. Update streams mein direction transitions required hain

TransitionRequired intervening operation
Output → inputfflush ya file-positioning operation
Input → outputFile-positioning operation, jab tak us input operation ne end-of-file encounter na kiya ho

Yeh sequencing requirements hain, sirf visual cursor movement nahi. Output flush start par wapas nahi laata aur newline transition replace nahi karti. Input-to-output mein fflush alone required positioning operation nahi. Successful fseek/fsetpos EOF indicator clear karte hain; generally stream error indicator clear nahi karte. Rewind error indicator bhi clear karta hai, par position failure check karne ka return value nahi.

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

int main(void)
{
    FILE *stream = tmpfile();
    if (stream == NULL) return EXIT_FAILURE;
    int status = EXIT_FAILURE;
    if (fputc('A', stream) == EOF) goto cleanup;
    if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
    int first = fgetc(stream);
    if (first != 'A') goto cleanup;
    if (fseek(stream, 0, SEEK_CUR) != 0) goto cleanup;
    if (fputc('B', stream) == EOF) goto cleanup;
    if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
    int again = fgetc(stream);
    int second = fgetc(stream);
    assert(again == 'A' && second == 'B');
    status = EXIT_SUCCESS;
cleanup:
    if (fclose(stream) == EOF) status = EXIT_FAILURE;
    return status;
}

4. Position token hamesha byte index nahi

Text stream mein portable fseek offset zero, ya same file ke successful earlier ftell ki value SEEK_SET ke saath use karta hai. Ftell value necessarily byte count nahi; us par arithmetic portable text-file navigation nahi. Binary streams mein positions beginning se characters count karti hain, par meaningful SEEK_END support required nahi. Fseek ka nonzero failure aur ftell ka -1L check karein.

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

int main(void)
{
    FILE *stream = tmpfile();
    if (stream == NULL) return EXIT_FAILURE;
    int status = EXIT_FAILURE;
    if (fputs("AB", stream) == EOF) goto cleanup;
    if (fseek(stream, 0, SEEK_SET) != 0) goto cleanup;
    int first = fgetc(stream);
    if (first != 'A') goto cleanup;
    fpos_t mark;
    if (fgetpos(stream, &mark) != 0) goto cleanup;
    int second = fgetc(stream);
    if (second != 'B') goto cleanup;
    if (fsetpos(stream, &mark) != 0) goto cleanup;
    int repeated = fgetc(stream);
    assert(repeated == 'B');
    status = EXIT_SUCCESS;
cleanup:
    if (fclose(stream) == EOF) status = EXIT_FAILURE;
    return status;
}

Fpos_t abstract position type hai; integer offset assume na karein. Fgetpos/fsetpos stream position aur applicable associated multibyte conversion state save/restore karte hain. Application variables restore, earlier file writes reverse ya parser ka own state recreate nahi karte. Ek file ka bookmark unrelated stream ko position karne ki permission nahi.

5. Bytes transfer karein; format separately design karein

Structure se sizeof record bytes write karna padding aur implementation-specific integer/pointer representations expose kar sakta hai. Binary mode representation portable nahi banata. Field sizes, ranges, byte order, versioning aur validation explicitly design karein. Transfer se pehle size-times-count arithmetic aur actual live buffer region validate karein. Successful block call schema validation ya durable storage ka proof nahi.

Primary references aur aage ki reading

Complete bounded encoding example ke liye External data formats padhein. Ismein fields structure ke memory layout se independently define hoti hain.

Aage badhne se pehle

  • Block I/O complete transferred elements report karta hai; poori request ki success promise nahi karta.
  • Position tokens aur text offsets ke specific stream rules hain.
  • Update streams mein reading-writing ke correct transitions chahiye.
In ideas ko alag rakhein
File position / Universal byte index
Saved stream position implementation state rakh sakti hai; hamesha simple external byte number nahi hoti.
Apne words mein samjhaayein

Short block read ke baad final record ya error decide karne se pehle kya inspect 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.

Kai elements likhne ki request par fwrite kya return karta hai?
Har choice ki explanation padhein
  1. Successfully written elements ki count.

    ✓ Sahi reasoning. Result elements count karta hai. Element size ek byte ho to yeh seedha byte count bhi deta hai.

  2. Hamesha total requested bytes ki count.

    Result completed elements batata hai aur short ho sakta hai.

  3. Guarantee ki later flush ya close fail nahi ho sakta.

    Buffered output mein later errors aa sakte hain; yahan ki success woh broader guarantee nahi.

C17

Agla idea padhne ke liye tayyar?

Mark this chapter as read whenever you feel ready.

CHAPTER 54 / 73

Is chapter mein

Block I/O, positions aur update streams

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