Lab06 TextDataFiles

download Lab06 TextDataFiles

of 8

Transcript of Lab06 TextDataFiles

  • 8/10/2019 Lab06 TextDataFiles

    1/8

    ICS 103: Computer Programming in C

    Lab #6: Text Data Files

    Objective:Learning how to use text data files for input and output.

    Data Files:When dealing with a large amount of data, it may be more convenient to read inputs and produce outputs,to and from files, rather than manually typing in inputs and printing outputs to the screen. Data files also

    provide data persistence.

    Difference between text files (ASCII files) and binary files

    While both binary and text files contain data stored as a series of bits binary values of !s and Os", the bitsin text files represent characters, while the bits in binary represent custom data. # plain text file contains noformatting codes whatsoever, no fonts, bold, italics or underlines, headers, footers or graphics.

    # typical plain text file contains several lines of text that are each followed by an $nd%of%Line $OL"character. #n $nd%of%&ile $O&" mar'er is placed after the final character, which signals the end of the file.

    Using data files fr in!"t and "t!"t

    (he process of using data files for input)output involves the following four steps:

    !% Declare pointer variables of type &*L$+ to represent the files within the program. (he declaration isof the form:

    FILE *pointerVariableName;

    where !interariable$a%eis any valid variable name.

    &xa%!le: FILE *infile, pointer !ariable for t"e input file *outfile; pointer !ariable for t"e output file

    -% Open the files for reading)writing using the f!enfunction. (he f!enfunction creates a correspondence between the pointerariable/ame for the file and the file0s external name. (he syntax of f!enis:

    pointerVariableName # fopen$fileE%ternalName, mo&e';

    &xa%!les:

    infile # fopen$(&ata)t%t(, (r('; open &ata)t%t for rea&ingoutfile # fopen$re+ult)t%t(, ('; open re+ult)t%t for riting

    $te:

    (he prototype for f!enis defined in the stdi'header file.

    f!enreturns the system named constant $ULLif the operation is not successful1 otherwise the

    starting address of the file is returned.

    *n dealing with files, it is always a good practice to verify if the file has been opened successfully beforeperforming read operations. (his is because reading from a file that has not been opened successfullywill results in run time error, causing the program to terminate abnormally.

    https://wiki.cs.auckland.ac.nz/enggen131/index.php/Fileshttps://wiki.cs.auckland.ac.nz/enggen131/index.php/Files
  • 8/10/2019 Lab06 TextDataFiles

    2/8

    (he following is an example of statements that handle the file not found error:

    if$infile ## N-LL' . printf$file not foun&/'; ++tem$(P-SE('; e%it$1'; e%it t"e program it" error 2o&e 1

    (he test can be done when attempting to open the file:

    if$$infile # fopen$(&ata)t%t(, (r('' ## N-LL'. printf$file not foun&/'; ++tem$(P-SE('; e%it$1'; e%it t"e program it" error 2o&e 1

    (he basic modes for opening files are:

    2r2 Open a text file for reading. $rror if the file does not exist

    2r32 Open a text file for reading and writing. $rror if the file does not exist

    2w2 Open a text file for writing and create the file if it does not exist. *f the file exists then ma'e it blan'.

    2w32Open a text file for reading and writing and create the file if it does not exist. *f the file exists then ma'e it

    blan'.

    2a2 Open a text file for appending writing at the end of file" and create the file if it does not exist.

    2a32 Open a text file for reading and appending and create the file if it does not exist.

    /ote: (he only modes that will be used in this course are 2r2 and 2w2. (he others are just mentioned for yourinformation.

    S!ecifying a file!at in f!en

    *f a data file is not in the same folder as the program accessing it, the full path of the file must be usedin the f!enstatement. (here are two ways to do this:

    separate folder names by a forward slash: )

    separate folder names by two bac' slashes: 44

    &xa%!les: FILE *infile1, *infile4, *outfile; infile1 # fopen$(5:term01i2+103 File+input5ata)t%t(, (r('; infile4 # fopen$(5:66term0166i2+103 File+66&ata4)t%t(, (r('; outfile # fopen$(E:667File+66output)t%t(, (('; // . . .

    5% 6ead)write from)to the files using file input)output functions.

    7ome file input functions:

    function Descriptionfscanffile8ointerariable, format7tring, #ddressList"1

    &xa%!le:f+2anf$infile, (8lf8lf8lf(, 9%, 9, 9';

    6eads values from the file into variables withcorresponding addresses in #ddressList, using theformats in format7tring. (he intsymbolic constant&*Fis returned when end%of%file mar'er isdetected.

    int ch 9 fgetcfile8ointerariable"1

    &xa%!le: int 2" # fget2$infile';

    6eads a character from the file.(he intsymbolicconstant &*Fis returned when end%of%file mar'er

    is detected.(he character is returned as int

    $te: When using fscanf to read data from a file, the programmer must 'now how the data is arrangedin the file.

    -

  • 8/10/2019 Lab06 TextDataFiles

    3/8

    +eading t te end f file

    (he &*F constant that is returned by fscanf and fgetcwhen the end%of%file mar'er is detected can beused as a sentinel:

    &xa%!le,: +eading ne line at a ti%e t te end f file

    "ile$f+2anf$infile, (8lf8lf8lf(, 9%, 9, 9' # E

  • 8/10/2019 Lab06 TextDataFiles

    4/8

    input)output functions &ile input)output functionsscanf("%d", &num); fscanf(stdin, "%d", &num);char ch = getchar( ); int ch = fgetc(stdin);printf("%d", num); fprintf(stdout, "%d", num);printf("ICS 1!"); fprintf(stdout, "ICS 1!");putchar(character); fputc(character, stdout)

    &xa%!le ,:(he program below reads milesfrom data'txt, displays the value on screen, and writes thecorresponding kilometers to res"lt'txt

    inc#ude $stdio.hinc#ude $std#i.hdefine 'S*+I-+ 1.

    int main(0oid) dou#e 2ms, mi#es;3I-+ 4infi#e, 4outfi#e;

    infi#e = fopen("data.t5t","r"); if(infi#e == 67--) printf("+rror8 3ai#ed to open data.t5t9n"); s:stem("*7S+");

    e5it(1); ?@ BB!5< @.?!->55-!!B @ BB!5< @

    *D 7O6$->?5- .?!

    ->-!!B

  • 8/10/2019 Lab06 TextDataFiles

    8/8

    Tas8 7: Rsing the same scres'txtfile of tas' -, write a program that reads the data from this file andassigns a letter grade to each student based on the following grading policy:

    Scre rade

    scoreS9 A> #

    @>T9 score TA> N

    ?

    T9scoreT?< DscoreT &

    Cour result should be stored in a file grades'txt. (he file must have three columns: *DQ, 7O6$ andL$(($6 U6#D$. Display each score with two digits after the decimal point.

    $te:7ince each *DQ is outside the range for int%5-B?B to 5-B?B", use type lng int %-!B@5?B to-!B@5?B" for *DQ1 the format specifier for lng intis the same asint namely 3d.

    Output file grades'txt:

    *DQ 7O6$ L$(($6 U6#D$->?@ BB!5< @.?! D->55-!!B