Top Banner

of 30

15412 File Handling(1)

Jul 07, 2018

Download

Documents

Gourav Kumar
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/18/2019 15412 File Handling(1)

    1/30

    File Handling

     The console oriented I/O operations pose

    two major problems:1. It becomes cumbersome and time

    consuming to handle large volumes ofdata through terminals.

    2. The entire data is lost when either theprogram is terminated or the computer isturned o.

     o it is necessar! to have a more"e#ible approach where data can bestored on dis$s and read whenevernecessar!%without destro!ing the

    data.This method emplo!es the concept

  • 8/18/2019 15412 File Handling(1)

    2/30

    File Operations

     There are dierent operations that

    can be carried out on a &le. Theseare: (reation of a new &le

    Opening an e#isting &le

    )eading from a &le

    *riting to a &le

    +oving to a speci&c location in a &le

    ,see$ing- (losing a &le

  • 8/18/2019 15412 File Handling(1)

    3/30

    Defning and Opening a File If we want to store data in the &le in the secondar!

    memor!%we must specif! certain things about the&le%to the operating s!stem.The! include:

    1. ilename

    2. ata tructure

    0. urpose  ata structure of a &le is de&ned as FILE in

    the librar! of standard I/O functionde&nitions.Therefore %all &les should be

    declared as t!pe FILE before the! areused.FILE is a de&ned data t!pe.

    FILE *p;

    p=open(“flename”,”mode”);

  • 8/18/2019 15412 File Handling(1)

    4/30

    +ode can be one of the following:

     “r”  Open an e#isting &le for reading onl!.

    “!”  Open a new &le for writing onl!. If a &le with the

    speci&ed fle-name currently exists, it will be destro!edand a new &le created in its place.

    “ a “ Open an e#isting &le for appending ,i.e.% for addingnew information at the end of the &le-. ' new &le

    will be created if the &le with the speci&ed fle-name does

    not exist.“r"“ Open an e#isting &le for both reading and writing.

    “!" 3 Open a new &le for both reading and writing. If a &lewith the speci&ed fle-name currently exists, it will bedestro!ed and a new &le created in its place.

    3 a" 3 Open an e#isting &le for both reading andappending. ' new &le will be created if the &le with thespeci&ed fle-name does not exist.

  • 8/18/2019 15412 File Handling(1)

    5/30

    4 include 5stdio.h5

    main, -

    6

    I78 9fp char ch

    fp ; fopen , 5)1.(5% 5r5 -

    while , 1 -

    6ch ; fgetc , fp -

    if , ch ;; 8O -

    brea$

    printf , 5

  • 8/18/2019 15412 File Handling(1)

    6/30

    open( ) perorms t#ree important tas$s !#en %o&open t#e fle in “r” mode'

    irstl! it searches on the dis$ the &le to be opened.

     Then it loads the &le from the dis$ into a place inmemor! called buer.

    It sets up a character pointer that points to the &rstcharacter of the buer.

     To read the &le>s contents from memor! there e#ists afunction called get( ) This has been used in ourprogram as%

    # = get ( p ) ;

    get( ) reads the character from the current pointer

    position% advances the pointer position so that it nowpoints to the ne#t character% and returns the characterthat is read% which we collected in the variable ch. ?otethat once the &le has been opened% we no longer referto the &le b! its name% but through the &le pointer p

  • 8/18/2019 15412 File Handling(1)

    7/30

    • In place of the function get( ) we could have aswell used the maro get( ) with the same eect

    • *e have used the function get( ) !it#in an

    indefnite !#ile loop There has to be a wa! tobrea$ out of this while. *hen shall we brea$ out...the moment we reach the end of &le. &t !#atis end o fle+ speial #arater, !#ose

    -.II /al&e is 01, signifes end o fle Thischaracter is inserted be!ond the last character inthe &le% when it is created.

    • *hile reading from the &le% when get( )encounters this special character% instead ofreturning the character that it has read, itret&rns t#e maro EOF 2#e EOF maro #as3een defned in t#e fle “stdio#

  • 8/18/2019 15412 File Handling(1)

    8/30

    If the &le opening fails due to an! of the reasons % theopen( ) &ntion ret&rns a /al&e 45LL (defned in“stdio#” as 6defne 45LL 7-. @ere is how this can behandled in a program...

    4include 5stdio.h5

    main, -

    6

    I78 9fp

    fp ; fopen , 5)1.(5% 5r5 -

    if , fp ;; ?A77 -

    6

    puts , 5cannot open &le5 - e#it, -

    =

    =

  • 8/18/2019 15412 File Handling(1)

    9/30

    .losing t#e File*hen we have &nished reading from the &le% we

    need to close it. This is done using the function

    lose( ) through the statement,

    fclose , fp -

    Once we close the &le we can no longer read from itusing get( ) &nless !e reopen t#e fle ?ote

    that to close the &le we don>t use the &lenamebut the &le pointer fp. On closing the &le thebuer associated with the &le is removed frommemor!.

    *hen we close this &le using lose( )t#ree operations !o&ld 3e perormed'

     The characters in the buer would be written tothe &le on the dis$.

    't the end of &le a character with '(II value 2B

  • 8/18/2019 15412 File Handling(1)

    10/30

    E4D OF FILE

    *hile reading data from a &le% if we want to read thecomplete &le i.e. the &le should be read till the end

    of data in it% then an end of &le mar$er of the &leshould be chec$ed.

     Two wa!s:

    8EOF' This character is present in &le at the end. 8g:

    while,a;getc ,fp-C;8O-

    putc ,a%fp-

    2. eo' feof,- is a macro which returns D if end of &leis not reached.If end of &le is reached%it returns non

    Eero value.eg:if,feof ,fp--

    printf ,3The end of &le has reachedF-

  • 8/18/2019 15412 File Handling(1)

    11/30

    9* .o&nt #ars, spaes, ta3s and ne!lines in afle *9

    4 include 5stdio.h5

    main, -

    6

    I78 9fp

    char ch int nol ; D% not ; D% nob ; D% noc ; D

    fp ; fopen , 5)1.(5% 5r5 -

    while , 1 -

    6ch ; fgetc , fp -

    if , ch ;; 8O -

    brea$

    nocGG

  • 8/18/2019 15412 File Handling(1)

    12/30

    if , ch ;; H H -

    nobGG

    if , ch ;; HnH -

    nolGG

    if , ch ;; HtH -

    notGG

    =

    fclose , fp -

    printf , 5n?umber of characters ;

  • 8/18/2019 15412 File Handling(1)

    13/30

    I9O Operations on Files2#e get() and p&t() F&ntions

     These are analogous to get#ar and p&t#ar

    functions and handle one character at a time.

    'ssume that a &le is opened with mode w and the &lepointer p. Then % the statement:

    p&t(,p);

     writes the character contained in the charactervariable c to the &le associated with FILE pointer fp.

    imilarl! % get is used to read a character from a &lethat has been opened in read mode.

    =get(p); The &le pointer moves b! one character position for

    ever! operation of get or p&t.

     The reading should be terminated when EOF isencounterd.

  • 8/18/2019 15412 File Handling(1)

    14/30

  • 8/18/2019 15412 File Handling(1)

    15/30

    if , ft ;; ?A77 -

    6

    puts , 5(annot open target &le5 -

    fclose , fs - e#it, -

    =

    while , 1 -

    6

    ch ; fgetc , fs -

    if , ch ;; 8O -

    brea$

    else

    fputc , ch% ft - =

    fclose , fs -

    fclose , ft -

    =

  • 8/18/2019 15412 File Handling(1)

    16/30

    2#e get! and p&t! F&ntions

     The get! and p&t! are integer

    oriented functions. The! are similarto get and p&t functions and areused to read and write integer

    values. These functions would be useful when

    we deal with integer data onl!.

    p&t!(integer,p);get!(p);

  • 8/18/2019 15412 File Handling(1)

    17/30

    -tring (line) I9O in Files)eading or writing strings of characters from and to &les is as

    eas! as reading and writing individual characters. @ere is aprogram that writes strings to a &le using the function p&ts( )

    9* :eei/es strings rom $e%3oard and !rites t#em to fle*9 

    4include 5stdio.h5

    main, -

    6

    I78 9fp

    char sJKDL

    if , fp ;; ?A77 -

    6puts , 5(annot open &le5 -

    e#it, -

    =

  • 8/18/2019 15412 File Handling(1)

    18/30

    printf , 5n8nter a few lines of te#t:n5 -

    while , strlen , gets , s - - M D -

    6

    fputs , s% fp -

    fputs , 5n5% fp -

    =

    fclose , fp - =

     The p&ts( - function then writes the contents ofthe arra! to the dis$. ince p&ts( ) does not

    automaticall! add a newline character to the endof the string% we must do this e#plicitl! to ma$eit easier to read the string bac$ from the &le.

  • 8/18/2019 15412 File Handling(1)

    19/30

    9* :eads strings rom t#e fle and displa%s t#em on sreen*9

    4include 5stdio.h5

    main, -

    6

    I78 9fp

    char sJKDL

    fp ; fopen , 5O8+.TNT5% 5r5 -

    if , fp ;; ?A77 -

    6

    puts , 5(annot open &le5 -

    e#it, -

    =while , fgets , s% P% fp - C; ?A77 -

    printf , 5

  • 8/18/2019 15412 File Handling(1)

    20/30

    'nd here is the output...

    hining and bright% the! are forever%

    so true about diamonds%

    more so of memories%

    especiall! !ours C

     The function gets( ) ta$es t#ree arg&ments

     The frst is t#e address where the string isstored% and the seond is t#e maim&mlengt# o t#e string. This argumentprevents fgets, - from reading in too long a

    string and over"owing the arra!. The t#irdarg&ment is t#e pointer to t#e str&t&reFILE. *hen all the lines from the &le havebeen read% we attempt to read one more line%in which case fgets, - returns a ?A77.

  • 8/18/2019 15412 File Handling(1)

    21/30

    2#e print and san F&ntionsprint( ) and san( ) li3rar% &ntions to read9!rite data rom9to

    fle

     This function is similar to print( ), e#cept that a FILE pointer is included asthe &rst argument. 's in print( ), we can format the data in a variet! ofwa!s% b! using print( ) In fact all the format conventions of print( -function wor$ with print( ) as well.

    print(p,”ontrol strings”,list);

    9*

  • 8/18/2019 15412 File Handling(1)

    22/30

    struct emp e

    fp ; fopen , 58+7OQ88.'T5% 5w5 -

    if , fp ;; ?A77 -

    6

    puts , 5(annot open &le5 -

    e#it, -

    =

    while , another ;; HQH -

    6printf , 5n8nter name% age and basic salar!: 5 -

    scanf , 5

  • 8/18/2019 15412 File Handling(1)

    23/30

    9* :ead reords rom a fle &sing str&t&re *9

    4include 5stdio.h5

    main, -

    6

    I78 9fp struct emp

    6

    char nameJRDL

    int age

    "oat bs

    =

    struct emp e

    fp ; fopen , 58+7OQ88.'T5% 5r5 -

    if , fp ;; ?A77 -

    6

    puts , 5(annot open &le5 - e#it, -

    =

    while , fscanf , fp% 5

  • 8/18/2019 15412 File Handling(1)

    24/30

    2et Files and inar% Files

    ' te#t &le contains onl! te#tual

    information li$e alphabets% digits andspecial s!mbols. In actualit! the'(II codes of these characters are

    stored in te#t &les. ' good e#ampleof a te#t &le is an! ( program % sa!)1.(.

    's against this% a binar! &le ismerel! a collection of b!tes. Thiscollection might be a compiledversion of a ( program ,sa!

    )1.8N8-% or music data stored in a

  • 8/18/2019 15412 File Handling(1)

    25/30

    4include 5stdio.h5

    main, -

    6

    I78 9fs% 9ft int ch

    fs ; fopen , 5pr1.e#e5% 5rb5 -

    if , fs ;; ?A77 -

    6

    puts , 5(annot open source &le5 - e#it, -

    =

    ft ; fopen , 5newpr1.e#e5% 5wb5 -

    if , ft ;; ?A77 -

    6puts , 5(annot open target &le5 -

    fclose , fs -

    e#it, -

    =

  • 8/18/2019 15412 File Handling(1)

    26/30

    while , 1 -

    6

    ch ; fgetc , fs -

    if , ch ;; 8O -

    brea$

    else

    fputc , ch% ft -

    =

    fclose , fs -

    fclose , ft -

    =

    Asing this program we can comfortabl! cop! te#t as well as binar!&les. ?ote that here we have opened the source and target &lesin 3rbF and 3wbF modes respectivel!. *hile opening the &le in te#tmode we can use either 3rF or 3rtF% but since te#t mode is thedefault mode we usuall! drop the Ut>.

  • 8/18/2019 15412 File Handling(1)

    27/30

    rom the programming angle there are three main areaswhere te#t and binar! mode &les are dierent. Theseare:

    @andling of newlines )epresentation of end of &le

    torage of numbers

    2et /ers&s inar% ode' 4e!lines• *e have alread! seen that% in te#t mode% a newline

    character is converted into the carriage returnlinefeedcombination before being written to the dis$.

    •  7i$ewise% the carriage returnlinefeed combination on

    the dis$ is converted bac$ into a newline when the &leis read b! a ( program.

    • @owever% if a &le is opened in binar! mode% asopposed to te#t mode% these conversions will not ta$eplace.

  • 8/18/2019 15412 File Handling(1)

    28/30

    2et /ers&s inar% ode' End o File

    •  The second dierence between te#t and binar!modes is in the wa! the endof&le is detected. In

    te#t mode% a special character% whose '(IIvalue is 2B% is inserted after the last character inthe &le to mar$ the end of &le. If this character isdetected at an! point in the &le% the read

    function would return the 8O signal to theprogram.

    • 's against this% there is no such specialcharacter present in the binar! mode &les to

    mar$ the end of &le. The binar! mode &les $eeptrac$ of the end of &le from the number ofcharacters present in the director! entr! of the&le.

  • 8/18/2019 15412 File Handling(1)

    29/30

    2et /ers&s inar% ode' -torage o4&m3ers

    •  The advantage of storing an integer number in binar! formis that it saves a lot of dis$ space.

    8g: If !ou want to store an integer value 1BR then it willconsume R b!tes of storage as each digit will be convertedto a '(II character which reVuires one b!te of storage.

    In binar! &les %1BR will consume onl! 2 b!tes for storage.

     '(II ormat

     R b!tes

    inar% Format

    2 b!tes

    1 B R

    D D D D D 1 D 1 11 11

  • 8/18/2019 15412 File Handling(1)

    30/30