module_5.doc

Upload: sruthy-sasi

Post on 04-Jun-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Module_5.doc

    1/12

    COMPUTER PROGRAMMING

    Module 5

    Data File

    Many applications require that information be written to or read from an auxiliary memory device. Suchinformation is stored on the memory device in the form of a data file. Thus, data files allow us to store informationpermanently, and to access and alter that information, whenever necessary. In C, an extensive set of library functionsis available for creating and processing data files.

    There are two different types of data files, called stream-oriented (or standard)data files, and systemoriented !or lowlevel" data files. Streamoriented data files are generally easier to wor# with and are therefore morecommonly used. Streamoriented data files can be subdivided into two categories. In the first category are tet !iles,consisting of consecutive characters. These characters can be interpreted as individual data items, or as componentsof strings or numbers.

    The second category of streamoriented data files, often referred to as un!ormatted data !iles, organi$es datainto bloc#s containing contiguous bytes of information. These bloc#s represent more complex data structures, such asarrays and structures. % separate set of library functions is available for processing stream oriented data files of thistype.

    "#stem-oriented data !iles are more closely related to the computer&s operating system than Streamoriented data files. They are somewhat more complicated to wor# with, though their use may be more efficient forcertain #inds of applications. % separate set of procedures, with accompanying library functions, is required to processsystemoriented data files.

    O$enin% And Closin% A Data File

    'hen wor#ing with a streamoriented data file, the first step is to establish a buffer area, where information istemporarily stored while being transferred between the computer&s memory and the data file. This buffer area allowsinformation to be read from or written to the data file more rapidly than would otherwise be possible.

    The buffer area is established by writing

    (I)* +ptvar

    where (I)* !uppercase letters required" is a special structure type that establishes the buffer area, and ptvar isa pointer variable that indicates the beginning of the buffer area. The structure type (I)* is defined within a systeminclude file, typically stdio. h. The pointer ptvar is often referred to as a stream pointer, or simply a stream.

    % data file must be opened before it can be created or processed. This associates the file name with the bufferarea !i.e., with the stream". It also specifies how the data file will be utili$ed, i.e., as a readonly file, a writeonly file, ora read-write file, in which both operations are permitted.

    The library function fopen is used to open a file. This function is typically written as

    Data File

    "tandard Data File "#stem Oriented Data File

    Un!ormattedTet

  • 8/14/2019 Module_5.doc

    2/12

    ptvar fopen !filename, file type"

    'here filename and file type are strings that represent the name of the data file and the manner in which thedata file will be utili$ed. The name chosen for the file name must be consistent with the rules for naming files, asdetermined by the computer&s operating system. The file type must be one of the strings shown below.

    File-T#$e Meanin%

    & r& /pen an existing file for reading only.

    &'& /pen a new file for writing only. If a file with the specified filename currently exists, it will bedestroyed and a new file created in its place.

    &a& /pen an existing file for appending !i.e., for adding new information at the end of the file". %new file will be created if the file with the specified filename does not exist.

    r& /pen an existing file for both reading and writing.

    '& /pen a new file for both reading and writing. If a file with the specified file name currentlyexists, it will be destroyed and a new file created in its place.

    &a& /pen an existing file for both reading and appending. % new file will be created if the file with

    the specified filename does not exist.

    The fopen function returns a pointer to the beginning of the buffer area associated with the file. % 01)) valueis returned if the file cannot be opened , for example, when an existing data file cannot be found.

    (inally, a data file must be closed at the end of the program. This can be accomplished with the library functionfclose.

    The syntax is simply

    fclose!ptvar"

    It is good programming practice to close a data file explicitly using the fclose function, though most Ccompilers will automatically close a data file at the end of program execution if a call to fclose is not present.

    % C program contains the following statements.

    2include 3stdio.h4(I)* +fptfpt fopen!5sample.dat&, 5w.". . . . .fclose!fpt"

    The first statement causes the header file stdio. h to be included in the program. The second statementdefines a pointer called fptwhich will point to a structure of type (I)*, indicating the beginning of the datafile bufferarea. 0ote that (I)* is defined in stdio. h.

    The third statement opens a new data file called sample. datas a writeonly file. Moreover, the fopen functionreturns a pointer to the beginning of the buffer area and assigns it to the pointer variable fpt. Thus, fpt points to thebuffer area associated with the data file sample. dat. %ll subsequent file processing statements !which are not shownexplicitly in this example" will access the data file via the pointer variable fpt rather than by the file name.

    (inally, the last statement closes the data file. 0ote that the argument is the pointer variable fpt, not the filename sample.dat.

    The value returned by the fopen function can be used to generate an error message if a data file cannot beopened, as illustrated in the next example.

  • 8/14/2019 Module_5.doc

    3/12

    % C program contains the following statements.

    2include 3stdio.h4

    2define 01)) 6

    main!"7

    (I)* +fpt

    fpt fopen!5Sample.dat5, 5r85"9if !fpt 01))"

    printf!5:n*;;/; Cannot open the designated file:n5"else7

    . . . . . /peratorD E D The bitwise%0> operator !E" compares each bit of its first operand to the corresponding bitof its second operand. If both bits are ?, the corresponding result bit is set to ?. /therwise, the corresponding result bitis set to 6.

    # 3 #

    6 6 6

    6 ? 6

    ? 6 6

    ? ? ?

    In the following example, the bitwise%0> operator !E" compares the bits of two integers, nNumAand nNumBD

    -- *xample of the bitwise%0> operatorint n0um%?, n0um, n0umC -- 6666666?, 666666??n0umC n0um% E n0um -- n0umC is now ?

    itwise*xclusive/; /peratorD N D The bitwiseexclusive/; operator !N" compares each bit of its first operand to thecorresponding bit of its second operand. If one bit is 6 and the other bit is ?, the corresponding result bit is set to ?./therwise, the corresponding result bit is set to 6.

  • 8/14/2019 Module_5.doc

    7/12

    4 #

    6 6 6

    6 ? ?

    ? 6 ?

    ? ? 6

    In the following example, the bitwiseexclusive/; operator !N" compares the bits of two integers, nNumAand nNumBD

    -- *xample of the bitwiseexclusive/; operatorint n0um%, n0um, n0umC -- 6666?66?, 666666??n0umC n0um% N n0um -- n0umC is now ?6D 6666?6?6

    itwiseInclusive/; /peratorD O D The bitwiseinclusive/; operator !O" compares each bit of its first operand to thecorresponding bit of its second operand. If either bit is ?, the corresponding result bit is set to ?. /therwise, thecorresponding result bit is set to 6.

    4 6 #

    6 6 6

    6 ? ?

    ? 6 ?

    ? ? ?

    In the following example, the bitwiseinclusive/; operator !O" compares the bits of two integers, nNumAand nNumBD

    -- *xample of the bitwiseinclusive/; operatorint n0um%, n0um, n0umC -- 6666?66?, 666666??n0umC n0um% O n0um -- n0umC is now ??D 6666?6??

    itwiseShift /perators D The shift operators perform appropriate shift by operator on the right to the operator on theleft. The right operator must be positive. The vacated bits are filled with $ero !i.e.There is NOwrap around".

    (or exampleDx33 R shifts the bits inxby R places to the left.

    SoDifx 666666?6 !binary" or R !decimal"

    thenD

    or 6 !decimal"

    %lsoD ifx 666666?6 !binary" or R !decimal"

    or Q !decimal"

    Therefore a shift left is equivalent to a multiplication by R. Similarly a shift right is equal to division by R

    NOTED Shifting is much faster than actual multiplication !+" or division !-" by R. So if you want fast multiplications ordivision by R use shifts.

    +it Fields

    it (ields allow the pac#ing of data in a structure. This is especially useful when memory or data storage is ata premium. Typical examplesD

  • 8/14/2019 Module_5.doc

    8/12

    ac#ing several ob9ects into a machine word. e.g. ? bit flags can be compacted Symbol tables in

    compilers.

    ;eading external file formats nonstandard file formats could be read in. *.g. bit integers.

    C lets us do this in a structure definition by putting Dbit length after the variable. i.e.

    struct pac#edUstruct 7unsigned int f?D?unsigned int fRD?unsigned int fD?unsigned int fVD?unsigned int typeDVunsigned int funnyUintD

    < pac#

    =ere the packed_struct contains 6 members: Four 1 bit flagsf1..f3, a bit t!pe and a "bit funn!_int.

    C automatically pac#s the above bit fields as compactly as possible, provided that the maximum length of thefield is less than or equal to the integer word length of the computer. If this is not the case then some compilers mayallow memory overlap for the fields whilst other would store the next field in the next word.

    %ccess members as usual viaD

    pac#.type W

    NOTED

    /nly n lower bits will be assigned to an n bit number. So type cannot ta#e values larger than ?P !V bits

    long".

    it fields are always converted to integer type for computation.

    Kou are allowed to mix FFnormal&& types with bit fields.

    The unsigneddefinition is important ensures that no bits are used as a flag.

    (requently device controllers !e.g.dis# drives" and the operating system need to communicate at a low level.>evice controllers contain several registerswhich may be pac#ed together in one integer !See (igure ".

    Fi%7 Eam$le Dis8 Controller Re%ister

    'e could define this register easily with bit fieldsD

    struct >ISXU;*JIST*;7

  • 8/14/2019 Module_5.doc

    9/12

    unsigned readyD? unsigned errorUoccuredD? unsigned dis#UspinningD? unsigned writeUprotectD? unsigned headUloadedD? unsigned errorUcodeDQ unsigned trac#D unsigned sectorDP unsigned commandDP

    ISXU;*JIST*;UM*M/;K we can assign a pointer of theabove structure to access the memory viaD

    struct >ISXU;*JIST*; +dis#Ureg !struct >ISXU;*JIST*; +" >ISXU;*JIST*;UM*M/;K

    Enumeration

    *numerated types contain a list of constants that can be addressed in integer values.

    'e can declare types and variables as follows.

    enum days7mon, tues, ..., sun

    < wee#

    enum days wee#?, wee#R

    NOTE9%s with arrays first enumerated name has index value 6. So mon has value 6, tues ?, and so on.

    wee#? and wee#R are variables.

    'e can define other valuesD

    enum escapes7

    bell F:a&,bac#space F:b&,tab F:t&,newline F:n&,vtab F:v&,return F:r&

  • 8/14/2019 Module_5.doc

    10/12

  • 8/14/2019 Module_5.doc

    11/12

    The preprocessor simply processes text it #nows virtually nothing about C syntax. It scans the input programtext, loo#ing for the directives in which the first character on a line is a &2&. 'hen it meets these directives, it ta#escertain actions, including other files to be processed, defining symbols, etc. It acts entirely on the program text and willhappily preprocess text which may be complete gibberish for the C compiler. This preprocessed text is then passedon to the C compiler itself, which chec#s the C syntax and, if it li#es it, consumes it, translating it into someintermediate code which is output, ready for input to the next phase.

    The C preprocessor provides four separate facilities that you can use as you see fitD

    Inclusion of header files. These are files of declarations that can be substituted into your program.

    Macro expansion. Kou can define macros, which are abbreviations for arbitrary fragments of C code, andthen the C preprocessor will replace the macros with their definitions throughout the program.

    Conditional compilation. 1sing special preprocessing directives, you can include or exclude parts of the

    program according to various conditions.

    )ine control. If you use a program to combine or rearrange source files into an intermediate file which is then

    compiled, you can use line control to inform the compiler of where each source line originally came from.

    Ma*ros

    reprocessor& is a translation phase that is applied to your source code before the compiler propergets its hands on it. Jenerally, the preprocessor performs textual substitutions on your source code. Macro is a type ofpreprocessor which replaces instances of one piece of text with another.

    % preprocessor line of the form

    2define nametext

    defines a macrowith the given name, having as its valuethe given replacement text. %fter that !for the rest of thecurrent source file", wherever the preprocessor sees that name, it will replace it with the replacement text. The name

  • 8/14/2019 Module_5.doc

    12/12

    follows the same rules as ordinary identifiers !it can contain only letters, digits, and underscores, and may not beginwith a digit". Since macros behave quite differently from normal variables !or functions", it is customary to give themnames which are all capital letters !or at least which begin with a capital letter". The replacement text can be absolutelyanythingit&s not restricted to numbers, or simple strings, or anything.

    The most common use for macros is to propagate various constants around and to ma#e them more selfdocumenting. 'e&ve been saying things li#e

    char lineY?66Z

    ...getline!line, ?66"

    but this is neither readable nor reliable it&s not necessarily obvious what all those ?66&s scattered around the programare, and if we ever decide that ?66 is too small for the si$e of the array to hold lines, we&ll have to remember to changethe number in two !or more" places. % much better solution is to use a macroD

    2define M%[)I0* ?66char lineYM%[)I0*Z...getline!line, M%[)I0*"

    0ow, if we ever want to change the si$e, we only have to do it in one place. The macro text M%[)I0* is #nown as

    symbolic constant.

    Macros with %rguments D Macros can also have arguments, 9ust as functions can.

    2define %;*%!x"!.?V+x+x"

    Then whenever the preprocessor finds the phrase %;*% !x" it expands it into the statement .?V + x + x. ecareful not to leave a blan# space between the macro template and its arguments while defining the macro. The entiremacro expansion should also be enclosed within parentheses.

    2 define %;*%!x"!.?V+x+x"2 include 3stdio.h4

    main!"7float xR.P,resultresult%;*%!x"printf!@BfA,result"