0% found this document useful (0 votes)
6 views

Lab-7-DataFiles Solutions

The document discusses using data files for input and output in C programs. It provides examples of opening files, reading and writing data, and closing files. Key steps are declaring FILE variables, opening files, reading and writing with fscanf and fprintf, and closing files after use.

Uploaded by

Salam R. Ammari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lab-7-DataFiles Solutions

The document discusses using data files for input and output in C programs. It provides examples of opening files, reading and writing data, and closing files. Key steps are declaring FILE variables, opening files, reading and writing with fscanf and fprintf, and closing files after use.

Uploaded by

Salam R. Ammari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

CSE 103: Computer Programming in C

Lab #7: Data Files


Objective:
By the end of the lab, students should know how to use data files for input and output.

Task 1: File Input/Output


Write Compile & Run the following C program in Dev-C++.
Save the source file in a new folder Lab7 as Lab7/program1.c
/*
This program reads one value of miles from a file, converts it into kilometres
and then write it in another file.
Before you run this program, make a file data.txt in the same folder.
The file must have one real value in it.
*/
#include <stdio.h>
#define KMS_PER_MILE 1.609
int main(void) {
double kms , miles;
FILE *infile , *outfile ; //declaring File variable
infile = fopen( "data.txt" , "r" );
if ( infile == NULL ) {
printf(“Sorry, input file not found\n");
exit(1);
}
outfile = fopen( "result.txt" , "w" );
if ( outfile == NULL ) {
printf(“Sorry, output file not created!");
exit(1);
}
fscanf( infile , "%lf" , &miles );
fprintf( outfile , "The distance in miles is %.2lf\n", miles);
kms = KMS_PER_MILE * miles;
fprintf(outfile , "That equals %.2lf kilometers\n" , kms ) ;
fclose(infile);
fclose(outfile);
return 0 ;
}

1. Run the Debugger on the program several times and write down your observations
Observations:

Page 1 of 9
2. When does the program dispaly “Sorry, input file not found"?
When this common error occure:
using data files is forgetting to create the input file before running the program.

3. When does the program dispaly “Sorry, output file not created!"?
When the program can’t creat result file.

4. Add usefull comments to the program (comments on the improtant steps for file
input/output)
/*
This program reads one value of miles from a file, converts it into
kilometres
and then write it in another file.
Before you run this program, make a file data.txt in the same
folder.
The file must have one real value in it.
*/
#include <stdio.h>
#define KMS_PER_MILE 1.609
int main(void) {
double kms , miles;
FILE *infile , *outfile ; //declaring File variable
// To open file for reading we use fopen
infile = fopen( "data.txt" , "r" );
if ( infile == NULL ) {
printf(“Sorry, input file not found\n");
exit(1);
}
outfile = fopen( "result.txt" , "w" );

Page 2 of 9
if ( outfile == NULL ) {
printf(“Sorry, output file not created!");
exit(1);
}
//Read from file using fscanf functions
fscanf( infile , "%lf" , &miles );
fprintf( outfile , "The distance in miles is %.2lf\n", miles);
kms = KMS_PER_MILE * miles;
fprintf(outfile , "That equals %.2lf kilometers\n" , kms ) ;
// close files by fclose function
fclose(infile);
fclose(outfile);
return 0 ;
}

Page 3 of 9
Task 2: Using EOF:
Write Compile & Run the following C program in Dev-C++.
Save the source file in as Lab7/program2.c
Compile & Run the C program in Dev-C++.
/*
This program reads text character by character from
a file and displays it on screen.
Before you run this program, make a file text.txt
in the same folder.
The file must have some text in it, such as your name
and address etc.
*/

#include <stdio.h>

int main(void)
{
FILE *in;
int status;
char ch;

in = fopen("text.txt", "r" );
if ( in == NULL ) {
printf(“Sorry, input file not found\n");
exit(1);
}

satus = fscanf(in ,"%c" , &ch );

while( status != EOF )


{
printf("%c" , ch);
status=fscanf(in,"%c",&ch);
}

fclose(in);

return 0;
}

1. Give a sample Output of the program?

Page 4 of 9
2. Run the Debugger on the program and watch the values of the two variables in and
status.
Write down your observations

Page 5 of 9
Task 3: fscanf in while Header:
Write Compile & Run the following C program in Dev-C++.
Save the source file in as Lab7/program3.c
Compile & Run the C program in Dev-C++.
/*
count no. of digits and other characters in a file
*/
#include <stdio.h>
int main (void)
{
FILE *in;
int cntDigits=0, cntOthers=0;
char ch;
in = fopen("text.txt","r");
if ( in == NULL ) {
printf("Sorry, input file not found\n");
exit(1);
}
while( fscanf(in,"%c",&ch) != EOF)
{
if ( ch >= '0' && ch <= '9' )
cntDigits++;
else
cntOthers++;
}
printf("Count of digits = %d \n", cntDigits);
printf("Count of others = %d \n", cntOthers);
fclose(in);

return 0;
}

Page 6 of 9
Task 4: fscanf in while Header:
Write Compile & Run the following C program in Dev-C++.
Save the source file in as Lab7/program5.c
Compile & Run the C program in Dev-C++.
/*
read scores from file and write score, grade (P/F) in a file
score.txt contains list of scores, one per line
*/
#include <stdio.h>
int main (void)
{
FILE *in, *out;
double score;
char grade;
in = fopen("scores.txt","r");
if ( in == NULL ) {
printf("Sorry, input file not found\n");
exit(1);
}
out = fopen("grades.txt","w");
if ( out == NULL ) {
printf("Sorry, output file not created\n");
exit(1);
}

while( fscanf(in,"%lf",&score) != EOF )


{
if (score >= 60)
grade = 'P';
else
grade = 'F';

fprintf(out, "%f \t %c \n", score, grade );


}
fclose(in);
fclose(out);

return 0;
}

Page 7 of 9
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, which may be difficult or inconvenient in the processing of large amounts of data.

The process of using data files for input/output involves four steps as follows:
1- Declare variables of type FILE to represent the files
FILE *infill, //pointer variable for the input file
*outfile; //pointer variable for the output file
2- Open the files for reading/writing using the fopen function.
infile = fopen("data.txt", "r");
outfile = fopen(“result.txt", “w");
Note: fopen returns NULL if the input file is not found.
In dealing with files, it is always a good practice to verify if the file has been opened sucessfully
before proceeding for read/write operations. This is because reading/writing on file which is not
opened sucessfully would results in run time error, causing the program to be terminated
abnormally.

Page 8 of 9
The follwing staements handle the file not found case by terminating the program in case the input
file is not opened succesfully.
if(infile==NULL) {
printf(“file not found”);
exit (1);
}

The basic modes for dealing with files are:

"r" Open for reading


"r+" Open for reading and writing
"w" Open for writing and create the file if it does not exist. If the file exists then make it blank.
Open for reading and writing and create the file if it does not exist. If the file exists then make it
"w+"
blank.
"a" Open for appending (writing at the end of file) and create the file if it does not exist.
"a+" Open for reading and appending and create the file if it does not exist.

The only modes that will be used in this course are "r" and "w". The others are just
mentioned for your information.
3- Read/write from/to the files using the fscanf and fprintf functions.
miles = fscanf (infile, " %lf", &miles);
Note: fscanf returns EOF if it encounters end of file.

fprintf(outfile, "That equals %.2f kilometers.\n", kms);

4- Close the files after processing the data using the fclose function.
fclose(infile);
fclose(outfile);
When you are finished using a file you must always close it. If you do not close a file, then some
of the data might not be written to it.

Page 9 of 9

You might also like