0% found this document useful (0 votes)
20 views8 pages

Screenshot 2023-03-09 at 11.10.26 PM

Uploaded by

omaraldoulab9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views8 pages

Screenshot 2023-03-09 at 11.10.26 PM

Uploaded by

omaraldoulab9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Lab05 – CIT125

Input/Output Data Files


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

Why 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.

How to work with data files in C#:

In C#, the process of using data files for input/output involves the following steps:

1. Declare variables of type StreamReader or StreamWriter.


2. Open/Create the files for reading/writing using the OpenText and CreateText/AppendText
methods.
3. Read/write from/to the files using the ReadLine and Write/WriteLine methods.
4. Close the files after processing the data using the Close method.

OR

Use ReadLine, ReadAllText, and ReadToEnd Functions

Examples
Example 1: This example writes the first name of student and his ID in Students.txt file. The file will be
saved in the same folder where the C# program is saved. [Use AppendText method if you do not want to
delete the previous contents of the file].
us ng System.IO;
class ReadWr te
{
publ c stat c vo d Ma n()
{
str ng StudentID, F rstName;
StudentID = "202209876";
F rstName = "Turk ";
F leStream target;
target = new F leStream("Student.txt", F leMode.OpenOrCreate);
StreamWr ter F leWr ter = new StreamWr ter(target);
F leWr ter.Wr teL ne("Welcome");
F leWr ter.Wr teL ne(StudentID + "," + F rstName);
F leWr ter.Close();
target.Close();
}
}

1
Example 2: This example reads from a file Students.txt. If the file exists in the same folder where C#
program is saved, then it reads the file line by line and print on the screen till it reaches to the end of
file. If the file does not exist, then it displays an error message in the message box.
us ng System;
us ng System.IO;
class ReadWr te
{
publ c stat c vo d Ma n()
{
nt counter = 0;
f (F le.Ex sts("Student.txt") == true)
{
foreach (str ng l ne n F le.ReadL nes("Student.txt"))
{
System.Console.Wr teL ne(l ne);
counter++;
}
Console.Wr teL ne("There were {0} l nes.", counter);
}
else
{

Console.Wr teL ne("F le Not Ex st");


}
}
}
Example 3: The program below reads miles from data.txt and writes the corresponding
kilometers to result.txt.
us ng System;
us ng System.IO;
class ReadWr te
{
publ c stat c vo d Ma n()
{
StreamWr ter outF le;
double kms;
const double KMS_flER_MILE = 1.609;
f (F le.Ex sts("data.txt") == true)
{
outF le = F le.CreateText("result.txt");

foreach (str ng m les n F le.ReadL nes("data.txt"))


{
kms = KMS_flER_MILE * Convert.ToDouble(m les);
outF le.Wr teL ne("{0} m les equals {1} k lometers.", m les, kms);
}

outF le.Close();
}
else
{
System.Console.Wr teL ne("Error open the f le");

}
}

2
Example 4: The program below calculates the sum and average score of a class in a quiz; it then
displays them on the screen. The quiz scores are read from an input file scores.txt.
us ng System;
us ng System.IO;
class ReadWr te
{
publ c stat c vo d Ma n()
{
double sum = 0, avg = 0;
nt count = 0;
f (F le.Ex sts("scores.txt") == true)
{
foreach (str ng Readscores n F le.ReadL nes("scores.txt"))
{
sum = sum + Convert.ToDouble(Readscores);
count++;
}
f (sum == 0)
{

System.Console.Wr teL ne("No data In the f le scores");


}
else
{
avg = sum / count;
System.Console.Wr teL ne("Sum= {0} average= {1} ", sum, avg);
}
}

else
{
System.Console.Wr teL ne("Error open the f le");
}
}
}

The contents of the input file scores.txt are:

5.5
8.5
10.0
9.9
7.3

The output: Sum= 41.2 average= 8.24

3
Laboratory Tasks:
Task01: Write a C# program that asks for 5 names and writes them to a file. Use loops to solve this
task.

Task02: Modify example2 such that in addition to display on the screen, it saves the data read into
another file. This way you create a copy program.

4
Laboratory Tasks:

Task03: Modify example4 such that it saves the results (sum and average) in the output file.

5
Laboratory Tasks:

Task04: A car park charges 3 Saudi Riyals per hour or any fraction of an hour for the first four hours of
parking. For hours in excess of 4, the charge is 1.50 Saudi Riyals per hour or any fraction of an hour.

6
Laboratory Tasks:

7
Laboratory Tasks:

Write a C# program that reads a textfile input.txt in which each line contains the number of hours a car
has been parked. As it does so it calculates and prints the parking charge of each car in an output file
output.txt.
It also calculates and prints the total parking charge.

Note:
 Use meaningful variable names.
 Your program must be general; it must work for any number of lines in the input file.
 The behaviour of your program and its output must be similar to the following sample program
run below:

Hint: Use math function Math.Ceiling method. The method rounds a double value x to the smallest double
integral value greater than x,
Example:
decimal decim_n1 = 5.4M;
decimal ceil_t1 = Math.Ceiling(decim_n1);
Console.WriteLine("Ceiling value = " + ceil_t1);
OutPut:
Ceiling value = 6

Sample input file Sample output file


3.5 Car# Hours Charge(SAR)
4.7 1 3.5 12.00
2.0 2 4.7 13.50
5.4 3 2.0 6.00
7.0 4 5.4 15.00
5 7.0 16.50
Total 63.00

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy