Lecture3_05

Embed Size (px)

Citation preview

  • 8/13/2019 Lecture3_05

    1/10

    LECTURE THREE FILES, STRUCTURES AND MEMORY

    ALLOCATION

    What these lecture notes coer

    These lecture notes should cover the following topics:

    File handling in C.

    Special streams stdin, stdoutand stderr.

    Defining new types of variable structand typedef.

    Dynamic memory (the point of pointers

    ! recap of new language features from wee" three.

    #ecture Three $ Files, Structures and %emory !llocation........................................................................&

    'hat these lecture notes cover...............................................................................................................&File handling in C...................................................................................................................................&

    ailing out in an emergency (the e)it command..................................................................................*+eading from a file fgets and fscanf......................................................................................................*

    Special streams stdin, stdout and stderr.................................................................................................-ow we S-/#D read input from the user (fgets, atoi and atof...................................................... ..

    !dding new types to C typedef and struct statements...........................................................................0Dynamic memory allocation................................................................................................................. .1

    ! note about returning pointers from functions.....................................................................................2! recap of synta) learned in wee" three................................................................................................3

    F!le han"l!n# !n C$

    To read and write files in C, we use a special pointer type, FILE *. FILE *is a special pointer type

    which contains information about how to open, close, write to and read from files.

    The first thing that we must do with any file is to open it using fopen. The fopen command has

    several formats. -ere are three e)amples:

    #define FILE3 "file3.txt"FILE *fptr; /* Declare a file pointer */char filename! "file.txt"; /* $trin% containin% a file name */

    fptr fopen &"file'.txt"("r"); /* pen file ' for readin% */

    fptr fopen &filename("+"); /* pen the file in filename for +ritin% ,his +ill delete the current contents of

    the file so -e 0EF1L */fptr fopen &FILE3("a"); /* pen the file in "file3.txt" for appendin% 2 that is to say that ne+ -its of the file +ill -e +ritten after the current file */

    4ach of these e)amples would set fptr to point at the re5uested file.

    IM%ORTANT RULE: /se a FILE *type variable (called a file pointer to store information about

    your file. /se fopento attempt to open the file in the appropriate way. fopenreturns 1LLif it

    fails to open the file. 6/## is a special pointer location which is set to indicate 7this pointer is notpointing at anything7.

    'e can chec" if we got the file open using:

    &

  • 8/13/2019 Lecture3_05

    2/10

    if &fptr 1LL) 4 printf &"5ro-lem openin% the file6n"); /* ,a7e some appropriate action 2 for example( return from

    main */ 8

    This is 4+++ C-4C896 (chec"ing that the file was open and is very important. 9 will tal" moreabout this later in the course.

    9f we have opened the file for writing or appending then we can use fprintf;ust the same as

    printfbut its first argument should be the name of the file pointer. For e)ample to print 7-ello

    'orld7 to the file output.t)t opened using fptr:

    #include 9stdio.h:int main&int ar%c( char *ar%!)4 FILE *fptr; fptr fopen &"+"( "output.txt"); if &fptr 1LL) 4

    fprintf &stderr( "ould not open output.txt6n"); return 2'; 8 fprintf &fptr( "6n"); fclose &fptr); return ?;8

    f course you can6n");

    *

  • 8/13/2019 Lecture3_05

    3/10

    /* Do somethin% a-out this error */ 8/* =e expected to read ' inte%er 2 chec7 this */if &noAread > ') 4 printf&"1na-le to read an int6n"); /* Do somethin% a-out this error */

    8

    IM%ORTANT RULE: The fscanffunction, li"e scanfreturns the number of arguments which it

    has successfully read. 9t returns the special value EF(end of file if it has reached the end of the file.

    ! better way to read from a file is the f%etsfunction. f%etsta"es three arguments $ a string to be

    read into, a number of characters to read and a FILE *pointer to read from. f%etsreturns a pointer

    to the string or, if it encounters end of file or some other reading error it returns 1LL.

    !n e)ample of use of f%etsis shown below:

    const int LE '???;

    FILE *fptr;char readline LE!;fptr fopen &"test.dat"("r");/* hec7 +e %ot the file open */+hile & f%ets&readline( LE( fptr) > 1LL) 4 /* Do somethin% +ith readline here */ 8

    Bou might find the +hileloop confusing here $ it is doing an awful lot of wor". 9t is actually 5uite

    common in C to put a function within the +hile loop. Finally, having read from a file, it is

    important that we 7close7 the file again. 'e do this using fclose.

    fclose&fptr);

    eginners often forget that fopen needs a file name but fclose needs a filepointer.

    S-ec!al strea's stdin, stdoutan" stderr

    !s mentioned in the previous wor"sheet there are three special streams of type FILE *which can be

    used with routines which ta"e FILE *arguments. These streams are all defined in stdio.h

    stdingets input from the "eyboard.

    stdout puts output to the screen.

    stderr puts output to an error stream (usually also the screen.

    The difference between printing to stderrand stdoutis subtle. Sometimes, output can beredirected into a file (often using a system called 7pipes7 which 9 will not tal" about on this course.

    4rrors often want to be handled differently. 9t is a good habit for a C programmer should print errorsli"e so:

    fprintf &stderr(",here is an error6n");

    9f a message is a critical error in your program you should print it li"e this rather than using printf

    although you will see no difference between them.

    Ho. .e SHOULD rea" !n-ut ro' the user )fgets,atoian" atof+

    The best way to read a line of input from the user is to use f%etswith the stdinfile handle.

  • 8/13/2019 Lecture3_05

    4/10

    char line'???!;f%ets &line( '???( stdin);/*0eads at most '??? characters from stdin or until the user pressesreturn */

    -aving read a line of te)t from the "eyboard into a string, we can then use various conversion utilities

    in stdli-.h

    For e)ample atoita"es a string and returns an integer. atofta"es a string and returns a dou-le.

    int i;dou-le f;char strin%! "3";char strin%! "'.'";

    i atoi &strin%); /* $ets i to 3 */f atof &strin%); /* $ets f to '.' */

    CAUTION f%etsfrom stdinputs a G6nGcharacter on the end of the string (from where the

    user typed G6nGto end the line. Sometimes we need to strip this G6nG to use the string. 'e can dothis by treating the string as a character array and moving along it until we find a G6nGthen replacing

    the G6nG with a G6?G.

    A""!n# ne. t(-es to C typedefan" structstate'ents

    Bou might be wondering about that peculiar FILE thing that seems to be usable li"e an intor a

    floatin functions. FILE is an e)ample of an important part of the C language "nown as a

    structure. ! structure is a built up part of the C language which behaves li"e a built in type. 'e can

    declare a group of associated variables which are associated as astructure.

    IM%ORTANT RULE: ! structstatement declares astructurewhich can hold information of

    e)isting types (or indeed other structures. ! struct should be declared at the top of the code or in aheader file.

    For e)ample, if we are writing a program for a ban", we might decide that an account is a fundamentaldata type in such a program. Therefore we declare a structurewhich deals with each account:

    struct account 4 char acctAholderH?!; /* ame of holder */ char address'??!; /* ddress of holder */ dou-le -alance; /* alance in pounds */ int acctAtype; /* type of account ' sain%s current */8;

    'e can declare variables to have this type. !nd we can access elements using the dot notation shownbelow:

    struct account ne+Aacct;strcpy &ne+Aacct.acctAholder( "$.

  • 8/13/2019 Lecture3_05

    5/10

    float interest;float rate '.KJ;interest ne+Aacct.-alance * rate / '??.?;printf &"ddin% interest of Bf6n"(interest);ne+Aacct.-alance interest;

    'e can ma"e our structloo" even more li"e a built in type such as intor float by using atypedefstatement. For e)ample:

    typedef struct ima%inaryAnum-er 4 dou-le realApart; dou-le ima%Apart;8 IMA1;

    we can then use the new type 9%!6/% pretty much wherever we can use an int. For e)ample:

    IMA1 x(y;dou-le a .?;x.realApart 3.?;

    x.ima%Apart a;

    'e can also use these typedeftypes in functions for e)ample:

    IMA1 multAima% &IMA1( IMA1);/* Function to multiply ima%inary num-ers */

    IMA1 multAima% &IMA1 x( IMA1 y)4 IMA1 ans; ans.realApart x.realApart*y.realApart 2 x.ima%Apart*y.ima%Apart; ans.ima%Apart x.realApart*y.ima%Apart y.realApart*x.ima%Apart; return ans;

    8

    IM%ORTANT RULE: typedef can be used to associate a label with a structure. y convention,

    we put our typedef names in !##C!S or at least 9nitial#etterCaps in order to distinguish them

    from built in types and variable names. #i"e a struct statement, typedef should be at the start

    of the code or in a header file.

    'e can even have arrays of typedefvariables. For e)ample:

    IMA1 points!;points?!.realApart 3.?;points?!.ima%Apart '.?;points'!.realApart @3.J;

    points'!.ima%Apart @.?;

    Bou can also use typedef to create another name for a built in type. For e)ample you could write:

    typedef int Len%th;

    the only common use for this is in defining things which are a pain in the nec" to type. For e)ample, ifyour program uses a lot of unsi%ned char values (recall that such a variable can store a number

    from E to * then you might want to:

    typedef unsi%ned char uchar;

    simply to save typing. (rogrammers are notoriously laGy.

    IM%ORTANT RULE: 'e can build structs up from other structs. For e)ample, we might

    want to define a rectangle in the imaginary plane by defining two of its corners. 'e could do so as

  • 8/13/2019 Lecture3_05

    6/10

    follows (assuming the previous definition of IMA1 has already been defined earlier in the

    program:

    typedef struct ima%Arect 4 IMA1 corner'; IMA1 corner;

    8 IMA0E,;

    'e can access the bits of the rectangle as follows:

    IMA0E, rect';rect'.corner'.ima%Apart 3.';rect'.corner'.realApart '.;rect'.corner.ima%Apart @.3;rect.corner.realApart '.N;

    Bou can also use typedef to create another name for a built in type. For e)ample you could write:

    typedef dou-le Len%th;

    This would allow you to use #ength wherever you could have used double. 4.g.Len%th roomAsiOe'?.N;Len%th roomA+idth'.3;

    This isn

  • 8/13/2019 Lecture3_05

    7/10

    #include 9stdli-.h:#include 9stdio.h:

    const int ALE'???;

    int main &int ar%c( char *ar%!)

    4 int *array; int i; int n; char strin%ALE!; printf &"6n"); return 2'; 8 for &i ?; i 9 n; i) arrayi! i; for &i ?; i 9 n; i) printf &"Element Bd is Bd6n"(i(arrayi!); free &array); return ?;8

    This code doesn

  • 8/13/2019 Lecture3_05

    8/10

    pointer which we don

  • 8/13/2019 Lecture3_05

    9/10

    dou-le *setAupAaccounts&int n)/* ode to process n ne+ accounts */4 dou-le *array; array &dou-le *)malloc&n*siOeof&dou-le)); if &array 1LL) 4

    fprintf &stderr("ut of memory>6n"); /* Qipe 2 do somethin% here */ 8 /* Do some set up thin%s here for accounts*/ . . . return array;8

    A reca- o s(nta* learne" !n .ee1 three

    Files in C can be opened and closed using fopenand fclosewhich use file handles of the type

    FILE *. fopenreturns 1LLif it fails to open a file.

    'e can write to a file using fprintf &file_ptr("

  • 8/13/2019 Lecture3_05

    10/10

    This defines !69%!# to be a data type which can be used li"e int, float or char. 'e have already seen

    F9#4 which was defined li"e this. ! structure defined with a typedef li"e this can be used li"e so:

    IL ti%er;

    tiger is now a variable li"e any other. 9t can be passed to functions and returned from them. 9ndividualparts of a structure can be accessed using the .notation as follows:

    ti%er.noAle%s N;ti%er.noAears ;sprintf &ti%er.name(",i%%er the ti%er");sprintf &ti%er.colour("mainly stripey");

    by tradition, typedefnames (that is the !69%!# part not the name of the variable, tiger are !##

    C!S or at least 9nitial#etterCaps.

    stdli-.h includes malloc and freewhich are used as follows:

    mallocis passed a siGe $ usually calculated using the siOeoffunction $ and returns a pointer to thatmuch free memory. 'hile not necessary (e)cept in CII H see note above, it is programmers often cast

    the mallocto the type of the pointer it is being assigned to. Some malloc e)amples are:

    int *siee;dou-le *-an7Aaccounts;char *userAname;

    siee &int *)malloc&'??*siOeof &int));-an7Aaccounts &dou-le *) malloc &'? * siOeof &dou-le));userAname &char *) malloc &N * siOeof &char));

    malloc returns 1LL if it cannot find any free memory to allocate. This should always be

    chec"ed.

    !nything malloced must be freed. ! freestatement ta"es as its argument a pointer to a memory

    location which was returned by malloc.

    &E