Home

A program to explain RANDOM ACCESS FILES

C Programming Language 118

Program

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int k;
    long int n;
    char c, ch;
    FILE *fp;

    fp = fopen("RANDOM", "w");
    if (fp == NULL)
    {
        printf("Error: unable to create RANDOM\n");
        exit(1);
    }

    printf("Type the content to store in RANDOM ... (Press CTRL+D to trigger EOF)\n\n");
    while ((c = getchar()) != EOF)
    {
        putc(c, fp);
    }

    printf("\nNumber of characters entered = %ld\n", ftell(fp));
    fclose(fp);

    fp = fopen("RANDOM", "r");
    n = 2L;
    k = fseek(fp, n, 0);

    printf("Character at position 2 = ");
    if (k == 0)
    {
        ch = getc(fp);
        putchar(ch);
        putchar('\n');
    }
    fclose(fp);

    printf("\n");
}

Result

Type the content to store in RANDOM ... (Press CTRL+D to trigger EOF)

abcdefghijklmnopqrstuvwxyz1234
Number of characters entered = 30
Character at position 2 = c


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments