Vous êtes sur la page 1sur 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 bits
in text files represent characters, while the bits in binary represent custom data. # plain text file contains no
formatting 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 is
of the form:
FILE *pointerVariableName;
where !inter#ariable$a%e is 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!en function. (he f!en function creates a
correspondence between the pointer.ariable/ame for the file and the file0s external name.
(he syntax of f!en is:
pointerVariableName # fopen$fileE%ternalName, mo&e';
&xa%!les:
infile # fopen$(&ata)t%t(, (r('; open &ata)t%t for rea&ing
outfile # fopen$*re+ult)t%t(, *,('; open re+ult)t%t for ,riting
$te:
(he prototype for f!en is defined in the stdi'( header file.
f!en returns the system named constant $ULL if 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 before
performing read operations. (his is because reading from a file that has not been opened successfully
will results in run time error, causing the program to terminate abnormally.
(he following is an example of statements that handle the file not found error:
if$infile ## N-LL' .
printf$*file not foun&/';
+0+tem$(P1-SE(';
e%it$1'; e%it t"e program ,it" error 2o&e 1
3
(he test can be done when attempting to open the file:
if$$infile # fopen$(&ata)t%t(, (r('' ## N-LL'.
printf$*file not foun&/';
+0+tem$(P1-SE(';
e%it$1'; e%it t"e program ,it" error 2o&e 1
3
(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'.
2w32
Open 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 your
information.
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 used
in the f!en statement. (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:6670File+66output)t%t(, (,(';
// . . .

5% 6ead)write from)to the files using file input)output functions.
7ome file input functions:
function Description
fscanffile8ointer.ariable, format7tring, #ddressList"1
&xa%!le:
f+2anf$infile, (8lf8lf8lf(, 9%, 90, 9:';
6eads values from the file into variables with
corresponding addresses in #ddressList, using the
formats in format7tring. (he int symbolic constant
&*F is returned when end%of%file mar'er is
detected.
int ch 9 fgetcfile8ointer.ariable"1
&xa%!le:
int 2" # fget2$infile';
6eads a character from the file. (he int symbolic
constant &*F is 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 arranged
in the file.
-
+eading t t(e end f file
(he &*F constant that is returned by fscanf and fgetc when the end%of%file mar'er is detected can be
used as a sentinel:
&xa%!le,: +eading ne line at a ti%e t t(e end f file
,"ile$f+2anf$infile, (8lf8lf8lf(, 9%, 90, 9:' ;# E<F'.
) ) )
3

$te: T(e ab-e l! is e."i-alent t:
int +tatu+ # f+2anf$infile, (8lf8lf8lf(, 9%, 90, 9:';
,"ile$+tatu+ ;# E<F'.
) ) )
+tatu+ # f+2anf$infile, (8lf8lf8lf(, 9%, 90, 9:';
3

&xa%!le/: +eading ne c(aracter at a ti%e t t(e end f file
2"ar 2";
,"ile$$2" # fget2$infile'' ;# E<F'.
) ) )
3
S%e file "t!"t f"nctins:
function Description
fprintffile8ointer.ariable, format7tring, expressionList"1
&xa%!le:
f!rintf("tfile0 1A-erage 2 3'/f4n10 s"% 5 c"nt)6
Write the values of the expressions in
expressionList to the file, using the formats in the
format string.
fprintffile8ointer.ariable, string"1
&xa%!le:
fprintf$outfile, (=el2ome to ICS 1036n(';
Write the string to the file.
fputccharacter, file8ointer.ariable"1
&xa%!le:
fput2$>?>, outfile';
Write the character to the file.
:% ,lose the files after processing the data using the fclse function.
(he function fclse is used to brea' the lin' established by the f!en between the file8ointer.ariable
and the external file. (he syntax of fclose is:
f2lo+e$filePointerVariable';
#fter this function call, the file8ointer.ariable can be used for another file.
&xa%!les:
f2lo+e$infile';
f2lo+e$outfile';
When you have finished using a file you must always close it. *f you do not close a file, then some of
the data might not be written to it.
Standard De-ice Files
When a program is run, the 'eyboard is assigned the internal filename stdin. 7imilarly, the output device
used for display usually the screen" is assigned the filename std"t. (hese two filenames are always
available for programmer use. (hus, the following are e;uivalent:
5
input)output functions &ile input)output functions
scanf("%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 miles from data'txt, displays the value on screen, and writes the
corresponding kilometers to res"lt'txt
"inc#ude $stdio.h%
"inc#ude $std#i&.h%
"define '(S)*+,)(I-+ 1../
int main(0oid) 1
dou&#e 2ms, mi#es;
3I-+ 4infi#e, 4outfi#e;
infi#e = fopen("data.t5t","r");
if(infi#e == 67--)1
printf("+rror8 3ai#ed to open data.t5t9n");
s:stem("*;7S+");
e5it(1);
<
outfi#e = fopen("resu#t.t5t","=");
fscanf(infi#e, "%#f", &mi#es);
fprintf(outfi#e, ">he distance in mi#es is %.?f.9n", mi#es);
2ms = '(S)*+,)(I-+ 4 mi#es;
fprintf(outfi#e, ">hat e@ua#s %.?f 2i#ometers.9n", 2ms);
fc#ose(infi#e);
fc#ose(outfi#e);
s:stem("*;7S+");
return ;
<
:
&xa%!le /: *n the program below the $O& $nd Of &ile" mar'er is used as a sentinel. (he program reads
its own text, character by character, and displays it on the screen.
,opy this program and save it as exa%!le/'c, then run it and you will see the whole program displayed on
the screen.
"inc#ude $stdio.h%
"inc#ude $std#i&.h%
int main (0oid)1
3I-+ 4in;
in = fopen("e5amp#e?.c","r");
if(in == 67--)1
printf("+rror8 3ai#ed to open e5amp#e?.c9n");
s:stem("*;7S+");
e5it(1);
<
char ch;
=hi#e(fscanf(in,"%c",&ch) A= +B3)
printf("%c",ch);

fc#ose(in);
s:stem("*;7S+");
return ;
<

*nstead of using fcanf and !rintf we can use fgetc and f!"tc:
"inc#ude $stdio.h%
"inc#ude $std#i&.h%
int main (0oid)1
3I-+ 4in;
in = fopen("e5amp#e?.c","r");
if(in == 67--)1
printf("+rror8 3ai#ed to open e5amp#e?.c9n");
s:stem("*;7S+");
e5it(1);
<
char ch;
=hi#e((ch = fgetc(in)) A= +B3)
fputc(ch, stdout);
fc#ose(in);
s:stem("*;7S+");
return ;
<
<
&xa%!le 7: (he program below calculates the sum and average score of a class in a ;ui=1 it then displays
them on the screen. (he ;ui= scores are read from an input file scres'txt.
"inc#ude $stdio.h%
"inc#ude $std#i&.h%
int main (0oid) 1
3I-+ 4infi#e;
dou&#e score, sum = , a0erage;
int count = , input)status;

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

=hi#e(fscanf(infi#e, "%#f", &score) A= +B3)1
printf("%f9n ", score);
sum C= score;
countCC;
<
a0erage = sum / count;
printf("9nSum of the scores is %f9n", sum);
printf(";0erage score is %.?f9n", a0erage);
fc#ose(infi#e);
s:stem("*;7S+");
return ;
<
(he contents of the input file scres'txt are:
!>.>
?.@ A.<
A.B B.B
5.? <.B @.!
B.5 ?.@
Laboratory (as's

/ote: Cou must use $O& controlled loop in all tas's.
(as' !: Write a program that reads a file data.txt shown below character by character. *t then displays the
number of digits, lowercase letters, uppercase letters, and other characters in an output file summary.txt as
shown below.
/ote: ,haracter digits are represented internally as an interval with increasing characters from D>E to DAE.
(hus, any character digit belongs to the interval FD>E,EAEG. (he same applies for letters i.e. a lowercase
letter belongs to the interval FDaE,E=EG, and an uppercase letter belongs to the interval FD#E,EHEG.

*nput file: data.txt Output file: summary.txt
'ad&atIJK<:<5
as+"LMB?<
!-A+KaNgOP
/umber of digits 9 !>
/umber of lowercase letters 9 A
/umber of uppercase letters 9 :
/umber of other characters 9 !!
$te: *f you donEt ta'e care of chec'ing new line character, you will get !5 for the number of other
characters.
?
Tas8 /: (he file scres'txt contains an un'nown number of data records for students in a certain section.
$ach data record i.e., each line in the scres'txt file" consists of two values: *DQ and the score of a
student.
Write a program that first reads the file to compute the average score of the students, it then reads the file
a second time to distribute the students into two output files, gd'txt containing those students whose
scores are greater or e;ual to the average, and !r'txt, containing those students who scored less than
the average.
9int: #fter the first reading, the file reading pointer reaches the end of the file. (here are two ways to
start reading from the beginning of the file again1 either close the file, then open it again or call rewind
function to reset the file reading pointer:
rewind file#ddress" 1
where fileAddress represents the &*L$+ variable name used in the f!en statement for scres'txt file.
*nput file scres'txt:
->?<-B ::.-:
->@<5> B<.5@
->B!5< @<.?!
-><-:! A!.<!
->:5-: <>.?!
->55<B ?@.-@
->-!!B <B.!!
Output files:
good.txt poor.txt
*D 7,O6$
->@<5> B<.5@
->B!5< @<.?!
-><-:! A!.<!
->55<B ?@.-@
*D 7,O6$
->?<-B ::.-:
->:5-: <>.?!
->-!!B <B.!!
$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 int is the same as int namely 3d.
B
Tas8 7: Rsing the same scres'txt file of tas' -, write a , program that reads the data from this file and
assigns a letter grade to each student based on the following grading policy:

Scre :rade
scoreS9 A> #
@>T9 score TA> N
?<T9scoreT@> ,
<>T9scoreT?< D
scoreT<> &
Cour result should be stored in a file grades'txt. (he file must have three columns: *DQ, 7,O6$ and
L$(($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 int is the same as int namely 3d.
Output file grades'txt:
*DQ 7,O6$ L$(($6 U6#D$
->?<-B ::.-: &
->@<5> B<.5@ ,
->B!5< @<.?! N
-><-:! A!.<! #
->:5-: <>.?! D
->55<B ?@.-@ ,
->-!!B <B.!! D
@

Vous aimerez peut-être aussi