SlideShare a Scribd company logo
CSWD1001
Programming Methods
Files
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
1
What we’ll learn
• Introduction to file input and output
• Using loops to process files
• Using files and arrays
• Processing records
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
2
File Input And Output
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
3
Three Steps using a File
• Open the file
• Opening a file – create a connection between the file and the program
• Opening an output file – creates the file on the disk and allows the program to
write data to it
• Opening an input file – allows the program to read data from the file
• Process the file – either written to the file (if it is an output file) or
read from the file (if it is an input file)
• Close the file – when the program is finished using the file, the file
must be closed
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
4
Two Types of files
• Text – contains data that has been encoded as text, using a scheme
such as ASCII or Unicode
• Binary - contains data that has not been converted to text
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
5
Text File
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
6
Binary File
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
7
Two Ways of Accessing a File
• Sequential access
• You access data from the beginning of the file to the end of the file
• Example: cassette tape players. If you want to listen to the last song on a
cassette tape, you have to either fast-forward over all of the songs that come
before it or listen to them
• There is no way to jump directly to a specific song
• Direct access / random access file
• You can jump directly to any piece of data in the file without reading the data
that comes before it
• Example: MP3 player. You can jump directly to any song that you want to
listen to
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
8
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
9
Performing File Operations
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
10
Five Operations
• Declaring a file
• Opening a file
• Reading a file
• Writing a file
• Closing a file
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
11
Concept File – Declaring
• Most languages support several types of fi les, but the broadest types
are fi les that can be used for input and fi les that can be used for
output.
• Each type of file has a data type defined in the language you are using.
• You declare files in the same way you declare variables and
constants—by giving each file a data type and an identifier.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
12
Declaration File – Declaring
fileMode fileName
fileMode fileName
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
13
Example File – Declaring
inputFile employeeData
outputFile updateData
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
14
File – Opening
• In most programming languages, before an application can
use a data file, it must open the file.
• Opening a file locates it on a storage device and associates a
variable name within your program with the file.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
15
Declaration File – Opening
Open filename “File Location”
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
16
Example File – Opening
Open employeeData “EmployeeData.dat”
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
17
File – Reading
• Before you can use stored data within a program, you must load the
data into computer memory.
• You never use the data values that are stored on a storage device
directly.
• Instead, you use a copy that is transferred into memory. When you
copy data from a file on a storage device into RAM, you read from
the file.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
18
Declaration of File – Reading
Read variable from fileData
Read variable from fileData
Read variable from fileData
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
19
Example File – Reading
Read name from employeeData
Read address from employeeData
Read payRate from employeeData
OR
Read name, address, payRate from employeeData
Read EmployeeRecord from employeeData
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
20
File – Writing
• When you store data in a computer fi le on a persistent
storage device, you write to the file.
• This means you copy data from RAM to the file.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
21
Declaration of File – Writing
Write variable to filename
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
22
Example File – Writing
write name, address, payRate to updatedData
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
23
File – Close
• When you finish using a fi le, the program should close the file - that
is, the file is no longer available to your application.
• Failing to close an input file (a file from which you are reading data)
usually does not present serious consequences; the data still exists in
the file.
• However, if you fail to close an output file (a file to which you are
writing data), the data might become inaccessible
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
24
Declaration of File – Close
Close filename
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
25
Example File – Close
Close inventoryFile
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
26
Example Use Case File Open, Write, Close
• A program that opens two fi les, reads employee data from
the input fi le, alters the employee’s pay rate, writes the
updated record to an output fi le, and closes the fi les.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
27
Pseudocode
Start
Declarations
InputFile employeeData
OutputFile updatedData
string name
string address
num payRate
num RAISE = 2.00
housekeeping()
while not eof
detailLoop()
Endwhile
finish()
End
housekeeping()
open employeeData "EmployeeData.dat"
open updatedData "UpdatedData.dat"
input name, address, payRate from employeeData
Return
detailLoop()
payRate = payRate + RAISE
output name, address, payRate to updatedData
input name, address, payRate from employeeData
Return
finish()
close employeeData
close updatedData
Return18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
28
Flowchart
Start
Declare
InputFile employeeData
OutputFilie updatedData
String name, address
Num payRate
Num RAISE = 2.00
housekeeping()
Not eof? detailLoop()
finish()
End
finish()
Close
employeeData
Close updatedData
Return
housekeeping()
Open employeeData
“EmployeeData.dat”
Open updatedData
“UpdatedData.dat”
Input name, address,
payRate from
employeeData
Return
detailLoop()
payRate = payRate + RAISE
Output name, address,
payRate to
updatedData
Input name, address,
payRate from
employeeData
Return
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
29
Files + Loop
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
30
Concept Using Loop to Process Files
• Files usually hold large amounts of data, and programs
typically use a loop to process the data in a file
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
31
Example Using Loop to Process Files
// Variable to hold the number of days
Declare Integer numDays
// Counter variable for the loop
Declare Integer counter
// Variable to hold an amount of sales
Declare Real sales
// Declare an output file.
Declare OutputFile salesFile
// Get the number of days.
Display "For how many days do you have
sales?"
Input numDays
// Open a file named sales.dat.
Open salesFile "sales.dat"
// Get the amount of sales for each day and
write it to the file.
For counter = 1 To numDays
// Get the sales for a day.
Display "Enter the sales for day #",
counter
Input sales
// Write the amount to the file.
Write salesFile sales
End For
// Close the file.
Close salesFile
Display "Data written to sales.dat."
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
32
Flowchart Start
Declare
Integer numDays,
counter
Real sales
outputFile salesFile
Display “For how
many days do you
have sales?”
Input numDays
Open salesFile “sales.dat”
A
A
Set counter = 1
Counter <=
numDays
Close salesFile
Display “Data
written to sales.dat”
End
Display “Enter the
sales for day #”,
counter
Input sales
Write slesFile sales
Set counter = counter + 1
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
33
Reading A File With A Loop And Detecting
The End of the File (EoF)
• Program needs some way of knowing when the end of the file has
been reached so it will not try to read beyond it
• Most programming languages provide a library function for this
purpose
• Eof function
• Accepts a file’s internal name as an argument, and returns True if the end of
the file has been reached or False if the end of the file has not been reached
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
34
Declaration EoF
Eof(internalFileName)
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
35
Example EoF
// Declare an input file.
Declare InputFile salesFile
// Declare a variable to hold a sales amount
// that is read from the file.
Declare Real sales
// Open the sales.dat file.
Open salesFile "sales.dat"
Display "Here are the sales amounts:"
// Read all of the items in the file
// and display them.
While NOT eof(salesFile)
Read salesFile sales
Display currencyFormat(sales)
End While
// Close the file.
Close salesFile
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
36
Flowchart Start
Declare
InputFile salesFile
Real sales
Open salesFile “sales.dat”
Not
eof(salesFile)
Close salesFile
End
Read slesFile sles
Display
currencyFormat(sales)
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
37
Files + Array
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
38
Concept Files + Arrays
• For some algorithms, files and arrays can be used together effectively.
• You can easily write a loop that saves the contents of an array to a file,
and vice versa.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
39
Example Files + Arrays: Open  Writes  Close
Constant Integer SIZE = 5
Declare Integer numbers[SIZE] = 10, 20, 30, 40, 50
// Counter variable to use in the loop.
Declare Integer index
// Declare an output file.
Declare OutputFile numberFile
// Open the values.dat file.
Open numberFile "values.dat“
// Write each array element to the file.
For index = 0 To SIZE - 1
Write numberFile numbers[index]
End For
// Close the file.
Close numberFile
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
40
Example Files + Arrays: Open  Read Close
Constant Integer SIZE = 5
Declare Integer numbers[SIZE]
// Counter variable to use in the loop, initialized
// with 0.
Declare Integer index = 0
// Declare an input file.
Declare InputFile numberFile
// Open the values.dat file.
Open numberFile "values.dat“
// Read the contents of the file into the array.
While (index <= SIZE – 1) AND (NOT eof(numberFile))
Write numberFile numbers[index]
Set index = index + 1
End While
// Close the file.
Close numberFile
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
41
Processing and Managing Record
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
42
Concepts Processing & Managing Records
• The data that is stored in a file is frequently organized in records
• A record is a complete set of data about an item
• A field is an individual piece of data within a record
• Example, we want to store data about employees in a file
• The file will contain a record for each employee
• Each record will be a collection of fields, such as name, ID number, and
department
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
43
Type of Processing and Managing Record
• Adding records
• Displaying records
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
44
Example Use Case Records Adding and
Displaying
• Midnight Coffee Roasters, Inc. is a small company that imports raw
coffee beans from around the world and roasts them to create a variety
of gourmet coffees.
• Julie, the owner of the company, has asked you to design a series of
programs that she can use to manage her inventory. After speaking
with her, you have determined that a file is needed to keep inventory
records.
• Each record should have two fields to hold the following data:
• Description: a string containing the name of the coffee
• Quantity in inventory: the number of pounds in inventory, as a real number
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
45
Pseudocode
// Variables for the fields
Declare String description
Declare Real quantity
// A variable to control the loop.
Declare String another = "Y"
// Declare an output file in append mode.
Declare OutputFile AppendMode coffeeFile
// Open the file.
Open coffeeFile "coffee.dat"
While toUpper(another) == "Y"
// Get the description.
Display "Enter the description."
Input description
// Get the quantity on hand.
Display "Enter the quantity on hand ", "(in pounds)."
Input quantity
// Append the record to the file.
Write coffeeFile description, quantity
// Determine whether the user wants to enter another
record.
Display "Do you want to enter another record? ",
Display "(Enter Y for yes, or anything else for no.)"
Input another
// Display a blank line.
Display
End While
// Close the file.
Close coffeeFile
Display "Data appended to coffee.dat."
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
46
// Variables for the fields
Declare String description
Declare Real quantity
// Declare an input file.
Declare InputFile coffeeFile
// Open the file.
Open coffeeFile "coffee.dat"
While NOT eof(coffeeFile)
// Read a record from the file.
Read coffeeFile description, quantity
// Display the record.
Display "Description: ", description, "Quantity: ", quantity, "
pounds"
End While
// Close the file.
Close coffeeFile
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
47
Flowchart – Exercise
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
48
Example Use Case Searching for a Record
• Julie has been using the first two programs that you designed for her.
• She now has several records stored in the coffee.dat file, and has asked you to
design another program that she can use to search for records.
• She wants to be able to enter a string and see a list of all the records containing
that string in the description field.
• For example, suppose the file contains the following records:
• If she enters “Sumatra” as the value to search for, the program should display all
of these records.
Description Quantity
Sumatra Dark Roast 12
Sumatra Medium Roast 30
Sumatra Decaf 20
Sumatra Organic Medium Roast 15
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
49
Pseuducode
// Variables for the fields
Declare String description
Declare Real quantity
// A variable to hold the search value.
Declare String searchValue
// A Flag to indicate whether the value was found.
Declare Boolean found = False
// Declare an input file.
Declare InputFile coffeeFile
// Get the value to search for.
Display "Enter a value to search for."
Input searchValue
// Open the file.
Open coffeeFile "coffee.dat"
While NOT eof(coffeeFile)
// Read a record from the file.
Read coffeeFile description, quantity
// If the record contains the search value, then display it.
If contains(description, searchValue) Then
// Display the record.
Display "Description: ", description, "Quantity: ",
quantity, " pounds"
// Set the found flag to true.
Set found = True
End If
End While
// If the value was not found in the file,
// display a message indicating so.
If NOT found Then
Display searchValue, " was not found."
End If
// Close the file.
Close coffeeFile
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
50
Flowchart – Exercise
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
51
Example Use Case Modifying for a Record
• Julie is very happy with the programs that you have designed so far. Your
next job is to design a program that she can use to modify the quantity field
in an existing record.
• This will allow her to keep the records up to date as coffee is sold or more
coffee is added to inventory.
• To modify a record in a sequential file, you must create a second temporary
file. You copy all of the original file’s records to the temporary file, but
when you get to the record that is to be modified, you do not write its old
contents to the temporary file. Instead, you write its new modified values to
the temporary file. Then, you finish copying any remaining records from the
original file to the temporary file.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
52
• The temporary file then takes the place of the original file. You delete
the original file and rename the temporary file, giving it the name that
the original file had on the computer’s disk. Here is the general
algorithm for your program:
1. Open the original file for input and create a temporary file for output.
2. Get the description field of the record to be modified and the new value for
the quantity field.
3. While not at the end of the original file:
Read a record.
If this record’s description field matches the description entered, then:
Write the new data to the temporary file.
Else write the existing record to the temporary file.
4. Close the original file and the temporary file.
5. Delete the original file.
6. Rename the temporary file, giving it the name of the original file.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
53
• Notice that at the end of the algorithm you delete the original file and then
rename the temporary file. Most programming languages provide a way to
perform these operations. In pseudocode we will use the Delete statement to
delete a file on the disk. You simply provide a string containing the name of
the file that you wish to delete, such as:
Delete "coffee.dat“
• To change the name of a file, we will use the Rename statement. For
example,
Rename "temp.dat", "coffee.dat“
• indicates that we are changing the name of the file temp.dat to coffee.dat.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
54
Pseudocode
// Variables for the fields
Declare String description
Declare Real quantity
// A variable to hold the search value.
Declare String searchValue
// A variable to hold the new quantity.
Declare Real newQuantity
// A Flag to indicate whether the value was found.
Declare Boolean found = False
// Declare an input file.
Declare InputFile coffeeFile
// Declare an output file to copy the original file to.
Declare OutputFile tempFile
// Open the original file.
Open coffeeFile "coffee.dat"
// Open the temporary file.
Open tempFile "temp.dat"
// Get the value to search for.
Display "Enter the coffee you wish to update."
Input searchValue
// Get the new quantity.
Display "Enter the new quantity."
Input newQuantity
While NOT eof(coffeeFile)
// Read a record from the file.
Read coffeeFile description, quantity
// Write either this record to the temporary
// file, or the new record if this is the
// one that is to be changed.
If description == searchValue Then
Write tempFile description, newQuantity
Set found = True
Else
Write tempFile description, quantity
End If
End While
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
55
// Close the original file.
Close coffeeFile
// Close the temporary file.
Close tempFile
// Delete the original file.
Delete "coffee.dat"
// Rename the temporary file.
Rename "temp.dat", "coffee.dat"
// Indicate whether the operation was successful.
If found Then
Display "The record was updated."
Else
Display searchValue, " was not found in the file."
End If
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
56
Flowchart – Exercise
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
57
Example Use Case Deleting a Record
• Your last task is to write a program that Julie can use to delete records
from the coffee.dat file. Like the process of modifying a record, the
process of deleting a record from a sequential access file requires that
you create a second temporary file.
• You copy all of the original file’s records to the temporary file, except
for the record that is to be deleted. The temporary file then takes the
place of the original file.
• You delete the original file and rename the temporary file, giving it the
name that the original file had on the computer’s disk.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
58
• Here is the general algorithm for your program:
1. Open the original file for input and create a temporary file for output.
2. Get the description field of the record to be deleted.
3. While not at the end of the original file:
Read a record.
If this record’s description field does not match the description entered, then:
Write the record to the temporary file.
4. Close the original file and the temporary file.
5. Delete the original file.
6. Rename the temporary file, giving it the name of the original file.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
59
Pseuducodeo
// Variables for the fields
Declare String description
Declare Real quantity
// A variable to hold the search value.
Declare String searchValue
// Declare an input file.
Declare InputFile coffeeFile
// Declare an output file to copy the original file to.
Declare OutputFile tempFile
// Open the files.
Open coffeeFile "coffee.dat"
Open tempFile "temp.dat"
// Get the value to search for.
Display "Enter the coffee you wish to delete."
Input searchValue
While NOT eof(coffeeFile)
// Read a record from the file.
Read coffeeFile description, quantity
// If this is not the record to delete, then
// write it to the temporary file.
If description != searchValue Then
Write tempFile description, quantity
End If
End While
// Close the two files.
Close coffeeFile
Close tempFile
// Delete the original file.
Delete "coffee.dat"
// Rename the temporary file.
Rename "temp.dat", "coffee.dat"
Display "The file has been updated."
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
60
Flowchart – Exercise
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
61
Summary
• A computer fi le is a collection of data stored on a non-volatile device
in a computer system. Although the contents of files differ, each file
occupies space on a section of a storage device, and each has a name
and a specific time of creation or last modification.
• When you use a data fi le in a program, you must declare it and open
it; opening a fi le associates an internal program identifier with the
name of a physical fi le on a storage device. When you read from a fi
le, the data is copied into memory. When you write to a fi le, the data
is copied from memory to a storage device. When you are done with a
fi le, you close it.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
62

More Related Content

Similar to 9 Files

2 Program Design Methodology
2 Program Design Methodology2 Program Design Methodology
2 Program Design Methodology
Kwan Lee
 
OMANTEL
OMANTELOMANTEL
Risk Analytics Using Knowledge Graphs / FIBO with Deep Learning
Risk Analytics Using Knowledge Graphs / FIBO with Deep LearningRisk Analytics Using Knowledge Graphs / FIBO with Deep Learning
Risk Analytics Using Knowledge Graphs / FIBO with Deep Learning
Cambridge Semantics
 
Data Regions: Modernizing your company's data ecosystem
Data Regions: Modernizing your company's data ecosystemData Regions: Modernizing your company's data ecosystem
Data Regions: Modernizing your company's data ecosystem
DataWorks Summit/Hadoop Summit
 
Fmi Open Data on S3
Fmi Open Data on S3Fmi Open Data on S3
Fmi Open Data on S3
Roope Tervo
 
Eecs6893 big dataanalytics-lecture1
Eecs6893 big dataanalytics-lecture1Eecs6893 big dataanalytics-lecture1
Eecs6893 big dataanalytics-lecture1
Aravindharamanan S
 
Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...
Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...
Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...
Ipro Tech
 
Building up a Data Science Team from Scratch
Building up a Data Science Team from ScratchBuilding up a Data Science Team from Scratch
Building up a Data Science Team from Scratch
Institute of Contemporary Sciences
 
Wounds to Wisdom Lessons Learned
Wounds to Wisdom Lessons LearnedWounds to Wisdom Lessons Learned
Wounds to Wisdom Lessons Learned
Ipro Tech
 
Importing Data - The Complete Course in All File Types and Data Tricks to Get...
Importing Data - The Complete Course in All File Types and Data Tricks to Get...Importing Data - The Complete Course in All File Types and Data Tricks to Get...
Importing Data - The Complete Course in All File Types and Data Tricks to Get...
Jim Kaplan CIA CFE
 
XPages - The Ties That Bind
XPages - The Ties That BindXPages - The Ties That Bind
XPages - The Ties That Bind
Michael McGarel
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
VishuSaini22
 
Cs 1114 - lecture-29
Cs 1114 - lecture-29Cs 1114 - lecture-29
Cs 1114 - lecture-29
Zeeshan Sabir
 
Preparing Import Files
Preparing Import FilesPreparing Import Files
"We're all in this together" - educating users on the importance of cyber sec...
"We're all in this together" - educating users on the importance of cyber sec..."We're all in this together" - educating users on the importance of cyber sec...
"We're all in this together" - educating users on the importance of cyber sec...
Jisc
 
Lecture 6 Data Driven Design
Lecture 6  Data Driven DesignLecture 6  Data Driven Design
Lecture 6 Data Driven Design
Sur College of Applied Sciences
 
ITES Case Study
ITES Case StudyITES Case Study
ITES Case Study
B Arvind Kumar
 
Intro To C++ - Class #21: Files
Intro To C++ - Class #21: FilesIntro To C++ - Class #21: Files
Intro To C++ - Class #21: Files
Blue Elephant Consulting
 
Prepare to Recover: Fully Protect Your Salesforce Data
Prepare to Recover: Fully Protect Your Salesforce Data Prepare to Recover: Fully Protect Your Salesforce Data
Prepare to Recover: Fully Protect Your Salesforce Data
Spanning Cloud Apps
 
file management functions
file management functionsfile management functions
file management functions
vaani pathak
 

Similar to 9 Files (20)

2 Program Design Methodology
2 Program Design Methodology2 Program Design Methodology
2 Program Design Methodology
 
OMANTEL
OMANTELOMANTEL
OMANTEL
 
Risk Analytics Using Knowledge Graphs / FIBO with Deep Learning
Risk Analytics Using Knowledge Graphs / FIBO with Deep LearningRisk Analytics Using Knowledge Graphs / FIBO with Deep Learning
Risk Analytics Using Knowledge Graphs / FIBO with Deep Learning
 
Data Regions: Modernizing your company's data ecosystem
Data Regions: Modernizing your company's data ecosystemData Regions: Modernizing your company's data ecosystem
Data Regions: Modernizing your company's data ecosystem
 
Fmi Open Data on S3
Fmi Open Data on S3Fmi Open Data on S3
Fmi Open Data on S3
 
Eecs6893 big dataanalytics-lecture1
Eecs6893 big dataanalytics-lecture1Eecs6893 big dataanalytics-lecture1
Eecs6893 big dataanalytics-lecture1
 
Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...
Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...
Cruise, Eat, Sleep, Repeat Best Practices on Setup and Customizing Your Case ...
 
Building up a Data Science Team from Scratch
Building up a Data Science Team from ScratchBuilding up a Data Science Team from Scratch
Building up a Data Science Team from Scratch
 
Wounds to Wisdom Lessons Learned
Wounds to Wisdom Lessons LearnedWounds to Wisdom Lessons Learned
Wounds to Wisdom Lessons Learned
 
Importing Data - The Complete Course in All File Types and Data Tricks to Get...
Importing Data - The Complete Course in All File Types and Data Tricks to Get...Importing Data - The Complete Course in All File Types and Data Tricks to Get...
Importing Data - The Complete Course in All File Types and Data Tricks to Get...
 
XPages - The Ties That Bind
XPages - The Ties That BindXPages - The Ties That Bind
XPages - The Ties That Bind
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 
Cs 1114 - lecture-29
Cs 1114 - lecture-29Cs 1114 - lecture-29
Cs 1114 - lecture-29
 
Preparing Import Files
Preparing Import FilesPreparing Import Files
Preparing Import Files
 
"We're all in this together" - educating users on the importance of cyber sec...
"We're all in this together" - educating users on the importance of cyber sec..."We're all in this together" - educating users on the importance of cyber sec...
"We're all in this together" - educating users on the importance of cyber sec...
 
Lecture 6 Data Driven Design
Lecture 6  Data Driven DesignLecture 6  Data Driven Design
Lecture 6 Data Driven Design
 
ITES Case Study
ITES Case StudyITES Case Study
ITES Case Study
 
Intro To C++ - Class #21: Files
Intro To C++ - Class #21: FilesIntro To C++ - Class #21: Files
Intro To C++ - Class #21: Files
 
Prepare to Recover: Fully Protect Your Salesforce Data
Prepare to Recover: Fully Protect Your Salesforce Data Prepare to Recover: Fully Protect Your Salesforce Data
Prepare to Recover: Fully Protect Your Salesforce Data
 
file management functions
file management functionsfile management functions
file management functions
 

Recently uploaded

Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 

Recently uploaded (20)

Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 

9 Files

  • 1. CSWD1001 Programming Methods Files 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 1
  • 2. What we’ll learn • Introduction to file input and output • Using loops to process files • Using files and arrays • Processing records 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 2
  • 3. File Input And Output 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 3
  • 4. Three Steps using a File • Open the file • Opening a file – create a connection between the file and the program • Opening an output file – creates the file on the disk and allows the program to write data to it • Opening an input file – allows the program to read data from the file • Process the file – either written to the file (if it is an output file) or read from the file (if it is an input file) • Close the file – when the program is finished using the file, the file must be closed 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 4
  • 5. Two Types of files • Text – contains data that has been encoded as text, using a scheme such as ASCII or Unicode • Binary - contains data that has not been converted to text 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 5
  • 6. Text File 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 6
  • 7. Binary File 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 7
  • 8. Two Ways of Accessing a File • Sequential access • You access data from the beginning of the file to the end of the file • Example: cassette tape players. If you want to listen to the last song on a cassette tape, you have to either fast-forward over all of the songs that come before it or listen to them • There is no way to jump directly to a specific song • Direct access / random access file • You can jump directly to any piece of data in the file without reading the data that comes before it • Example: MP3 player. You can jump directly to any song that you want to listen to 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 8
  • 9. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 9
  • 10. Performing File Operations 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 10
  • 11. Five Operations • Declaring a file • Opening a file • Reading a file • Writing a file • Closing a file 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 11
  • 12. Concept File – Declaring • Most languages support several types of fi les, but the broadest types are fi les that can be used for input and fi les that can be used for output. • Each type of file has a data type defined in the language you are using. • You declare files in the same way you declare variables and constants—by giving each file a data type and an identifier. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 12
  • 13. Declaration File – Declaring fileMode fileName fileMode fileName 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 13
  • 14. Example File – Declaring inputFile employeeData outputFile updateData 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 14
  • 15. File – Opening • In most programming languages, before an application can use a data file, it must open the file. • Opening a file locates it on a storage device and associates a variable name within your program with the file. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 15
  • 16. Declaration File – Opening Open filename “File Location” 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 16
  • 17. Example File – Opening Open employeeData “EmployeeData.dat” 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 17
  • 18. File – Reading • Before you can use stored data within a program, you must load the data into computer memory. • You never use the data values that are stored on a storage device directly. • Instead, you use a copy that is transferred into memory. When you copy data from a file on a storage device into RAM, you read from the file. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 18
  • 19. Declaration of File – Reading Read variable from fileData Read variable from fileData Read variable from fileData 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 19
  • 20. Example File – Reading Read name from employeeData Read address from employeeData Read payRate from employeeData OR Read name, address, payRate from employeeData Read EmployeeRecord from employeeData 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 20
  • 21. File – Writing • When you store data in a computer fi le on a persistent storage device, you write to the file. • This means you copy data from RAM to the file. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 21
  • 22. Declaration of File – Writing Write variable to filename 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 22
  • 23. Example File – Writing write name, address, payRate to updatedData 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 23
  • 24. File – Close • When you finish using a fi le, the program should close the file - that is, the file is no longer available to your application. • Failing to close an input file (a file from which you are reading data) usually does not present serious consequences; the data still exists in the file. • However, if you fail to close an output file (a file to which you are writing data), the data might become inaccessible 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 24
  • 25. Declaration of File – Close Close filename 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 25
  • 26. Example File – Close Close inventoryFile 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 26
  • 27. Example Use Case File Open, Write, Close • A program that opens two fi les, reads employee data from the input fi le, alters the employee’s pay rate, writes the updated record to an output fi le, and closes the fi les. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 27
  • 28. Pseudocode Start Declarations InputFile employeeData OutputFile updatedData string name string address num payRate num RAISE = 2.00 housekeeping() while not eof detailLoop() Endwhile finish() End housekeeping() open employeeData "EmployeeData.dat" open updatedData "UpdatedData.dat" input name, address, payRate from employeeData Return detailLoop() payRate = payRate + RAISE output name, address, payRate to updatedData input name, address, payRate from employeeData Return finish() close employeeData close updatedData Return18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 28
  • 29. Flowchart Start Declare InputFile employeeData OutputFilie updatedData String name, address Num payRate Num RAISE = 2.00 housekeeping() Not eof? detailLoop() finish() End finish() Close employeeData Close updatedData Return housekeeping() Open employeeData “EmployeeData.dat” Open updatedData “UpdatedData.dat” Input name, address, payRate from employeeData Return detailLoop() payRate = payRate + RAISE Output name, address, payRate to updatedData Input name, address, payRate from employeeData Return 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 29
  • 30. Files + Loop 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 30
  • 31. Concept Using Loop to Process Files • Files usually hold large amounts of data, and programs typically use a loop to process the data in a file 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 31
  • 32. Example Using Loop to Process Files // Variable to hold the number of days Declare Integer numDays // Counter variable for the loop Declare Integer counter // Variable to hold an amount of sales Declare Real sales // Declare an output file. Declare OutputFile salesFile // Get the number of days. Display "For how many days do you have sales?" Input numDays // Open a file named sales.dat. Open salesFile "sales.dat" // Get the amount of sales for each day and write it to the file. For counter = 1 To numDays // Get the sales for a day. Display "Enter the sales for day #", counter Input sales // Write the amount to the file. Write salesFile sales End For // Close the file. Close salesFile Display "Data written to sales.dat." 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 32
  • 33. Flowchart Start Declare Integer numDays, counter Real sales outputFile salesFile Display “For how many days do you have sales?” Input numDays Open salesFile “sales.dat” A A Set counter = 1 Counter <= numDays Close salesFile Display “Data written to sales.dat” End Display “Enter the sales for day #”, counter Input sales Write slesFile sales Set counter = counter + 1 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 33
  • 34. Reading A File With A Loop And Detecting The End of the File (EoF) • Program needs some way of knowing when the end of the file has been reached so it will not try to read beyond it • Most programming languages provide a library function for this purpose • Eof function • Accepts a file’s internal name as an argument, and returns True if the end of the file has been reached or False if the end of the file has not been reached 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 34
  • 35. Declaration EoF Eof(internalFileName) 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 35
  • 36. Example EoF // Declare an input file. Declare InputFile salesFile // Declare a variable to hold a sales amount // that is read from the file. Declare Real sales // Open the sales.dat file. Open salesFile "sales.dat" Display "Here are the sales amounts:" // Read all of the items in the file // and display them. While NOT eof(salesFile) Read salesFile sales Display currencyFormat(sales) End While // Close the file. Close salesFile 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 36
  • 37. Flowchart Start Declare InputFile salesFile Real sales Open salesFile “sales.dat” Not eof(salesFile) Close salesFile End Read slesFile sles Display currencyFormat(sales) 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 37
  • 38. Files + Array 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 38
  • 39. Concept Files + Arrays • For some algorithms, files and arrays can be used together effectively. • You can easily write a loop that saves the contents of an array to a file, and vice versa. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 39
  • 40. Example Files + Arrays: Open  Writes  Close Constant Integer SIZE = 5 Declare Integer numbers[SIZE] = 10, 20, 30, 40, 50 // Counter variable to use in the loop. Declare Integer index // Declare an output file. Declare OutputFile numberFile // Open the values.dat file. Open numberFile "values.dat“ // Write each array element to the file. For index = 0 To SIZE - 1 Write numberFile numbers[index] End For // Close the file. Close numberFile 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 40
  • 41. Example Files + Arrays: Open  Read Close Constant Integer SIZE = 5 Declare Integer numbers[SIZE] // Counter variable to use in the loop, initialized // with 0. Declare Integer index = 0 // Declare an input file. Declare InputFile numberFile // Open the values.dat file. Open numberFile "values.dat“ // Read the contents of the file into the array. While (index <= SIZE – 1) AND (NOT eof(numberFile)) Write numberFile numbers[index] Set index = index + 1 End While // Close the file. Close numberFile 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 41
  • 42. Processing and Managing Record 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 42
  • 43. Concepts Processing & Managing Records • The data that is stored in a file is frequently organized in records • A record is a complete set of data about an item • A field is an individual piece of data within a record • Example, we want to store data about employees in a file • The file will contain a record for each employee • Each record will be a collection of fields, such as name, ID number, and department 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 43
  • 44. Type of Processing and Managing Record • Adding records • Displaying records 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 44
  • 45. Example Use Case Records Adding and Displaying • Midnight Coffee Roasters, Inc. is a small company that imports raw coffee beans from around the world and roasts them to create a variety of gourmet coffees. • Julie, the owner of the company, has asked you to design a series of programs that she can use to manage her inventory. After speaking with her, you have determined that a file is needed to keep inventory records. • Each record should have two fields to hold the following data: • Description: a string containing the name of the coffee • Quantity in inventory: the number of pounds in inventory, as a real number 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 45
  • 46. Pseudocode // Variables for the fields Declare String description Declare Real quantity // A variable to control the loop. Declare String another = "Y" // Declare an output file in append mode. Declare OutputFile AppendMode coffeeFile // Open the file. Open coffeeFile "coffee.dat" While toUpper(another) == "Y" // Get the description. Display "Enter the description." Input description // Get the quantity on hand. Display "Enter the quantity on hand ", "(in pounds)." Input quantity // Append the record to the file. Write coffeeFile description, quantity // Determine whether the user wants to enter another record. Display "Do you want to enter another record? ", Display "(Enter Y for yes, or anything else for no.)" Input another // Display a blank line. Display End While // Close the file. Close coffeeFile Display "Data appended to coffee.dat." 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 46
  • 47. // Variables for the fields Declare String description Declare Real quantity // Declare an input file. Declare InputFile coffeeFile // Open the file. Open coffeeFile "coffee.dat" While NOT eof(coffeeFile) // Read a record from the file. Read coffeeFile description, quantity // Display the record. Display "Description: ", description, "Quantity: ", quantity, " pounds" End While // Close the file. Close coffeeFile 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 47
  • 48. Flowchart – Exercise 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 48
  • 49. Example Use Case Searching for a Record • Julie has been using the first two programs that you designed for her. • She now has several records stored in the coffee.dat file, and has asked you to design another program that she can use to search for records. • She wants to be able to enter a string and see a list of all the records containing that string in the description field. • For example, suppose the file contains the following records: • If she enters “Sumatra” as the value to search for, the program should display all of these records. Description Quantity Sumatra Dark Roast 12 Sumatra Medium Roast 30 Sumatra Decaf 20 Sumatra Organic Medium Roast 15 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 49
  • 50. Pseuducode // Variables for the fields Declare String description Declare Real quantity // A variable to hold the search value. Declare String searchValue // A Flag to indicate whether the value was found. Declare Boolean found = False // Declare an input file. Declare InputFile coffeeFile // Get the value to search for. Display "Enter a value to search for." Input searchValue // Open the file. Open coffeeFile "coffee.dat" While NOT eof(coffeeFile) // Read a record from the file. Read coffeeFile description, quantity // If the record contains the search value, then display it. If contains(description, searchValue) Then // Display the record. Display "Description: ", description, "Quantity: ", quantity, " pounds" // Set the found flag to true. Set found = True End If End While // If the value was not found in the file, // display a message indicating so. If NOT found Then Display searchValue, " was not found." End If // Close the file. Close coffeeFile 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 50
  • 51. Flowchart – Exercise 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 51
  • 52. Example Use Case Modifying for a Record • Julie is very happy with the programs that you have designed so far. Your next job is to design a program that she can use to modify the quantity field in an existing record. • This will allow her to keep the records up to date as coffee is sold or more coffee is added to inventory. • To modify a record in a sequential file, you must create a second temporary file. You copy all of the original file’s records to the temporary file, but when you get to the record that is to be modified, you do not write its old contents to the temporary file. Instead, you write its new modified values to the temporary file. Then, you finish copying any remaining records from the original file to the temporary file. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 52
  • 53. • The temporary file then takes the place of the original file. You delete the original file and rename the temporary file, giving it the name that the original file had on the computer’s disk. Here is the general algorithm for your program: 1. Open the original file for input and create a temporary file for output. 2. Get the description field of the record to be modified and the new value for the quantity field. 3. While not at the end of the original file: Read a record. If this record’s description field matches the description entered, then: Write the new data to the temporary file. Else write the existing record to the temporary file. 4. Close the original file and the temporary file. 5. Delete the original file. 6. Rename the temporary file, giving it the name of the original file. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 53
  • 54. • Notice that at the end of the algorithm you delete the original file and then rename the temporary file. Most programming languages provide a way to perform these operations. In pseudocode we will use the Delete statement to delete a file on the disk. You simply provide a string containing the name of the file that you wish to delete, such as: Delete "coffee.dat“ • To change the name of a file, we will use the Rename statement. For example, Rename "temp.dat", "coffee.dat“ • indicates that we are changing the name of the file temp.dat to coffee.dat. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 54
  • 55. Pseudocode // Variables for the fields Declare String description Declare Real quantity // A variable to hold the search value. Declare String searchValue // A variable to hold the new quantity. Declare Real newQuantity // A Flag to indicate whether the value was found. Declare Boolean found = False // Declare an input file. Declare InputFile coffeeFile // Declare an output file to copy the original file to. Declare OutputFile tempFile // Open the original file. Open coffeeFile "coffee.dat" // Open the temporary file. Open tempFile "temp.dat" // Get the value to search for. Display "Enter the coffee you wish to update." Input searchValue // Get the new quantity. Display "Enter the new quantity." Input newQuantity While NOT eof(coffeeFile) // Read a record from the file. Read coffeeFile description, quantity // Write either this record to the temporary // file, or the new record if this is the // one that is to be changed. If description == searchValue Then Write tempFile description, newQuantity Set found = True Else Write tempFile description, quantity End If End While 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 55
  • 56. // Close the original file. Close coffeeFile // Close the temporary file. Close tempFile // Delete the original file. Delete "coffee.dat" // Rename the temporary file. Rename "temp.dat", "coffee.dat" // Indicate whether the operation was successful. If found Then Display "The record was updated." Else Display searchValue, " was not found in the file." End If 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 56
  • 57. Flowchart – Exercise 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 57
  • 58. Example Use Case Deleting a Record • Your last task is to write a program that Julie can use to delete records from the coffee.dat file. Like the process of modifying a record, the process of deleting a record from a sequential access file requires that you create a second temporary file. • You copy all of the original file’s records to the temporary file, except for the record that is to be deleted. The temporary file then takes the place of the original file. • You delete the original file and rename the temporary file, giving it the name that the original file had on the computer’s disk. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 58
  • 59. • Here is the general algorithm for your program: 1. Open the original file for input and create a temporary file for output. 2. Get the description field of the record to be deleted. 3. While not at the end of the original file: Read a record. If this record’s description field does not match the description entered, then: Write the record to the temporary file. 4. Close the original file and the temporary file. 5. Delete the original file. 6. Rename the temporary file, giving it the name of the original file. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 59
  • 60. Pseuducodeo // Variables for the fields Declare String description Declare Real quantity // A variable to hold the search value. Declare String searchValue // Declare an input file. Declare InputFile coffeeFile // Declare an output file to copy the original file to. Declare OutputFile tempFile // Open the files. Open coffeeFile "coffee.dat" Open tempFile "temp.dat" // Get the value to search for. Display "Enter the coffee you wish to delete." Input searchValue While NOT eof(coffeeFile) // Read a record from the file. Read coffeeFile description, quantity // If this is not the record to delete, then // write it to the temporary file. If description != searchValue Then Write tempFile description, quantity End If End While // Close the two files. Close coffeeFile Close tempFile // Delete the original file. Delete "coffee.dat" // Rename the temporary file. Rename "temp.dat", "coffee.dat" Display "The file has been updated." 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 60
  • 61. Flowchart – Exercise 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 61
  • 62. Summary • A computer fi le is a collection of data stored on a non-volatile device in a computer system. Although the contents of files differ, each file occupies space on a section of a storage device, and each has a name and a specific time of creation or last modification. • When you use a data fi le in a program, you must declare it and open it; opening a fi le associates an internal program identifier with the name of a physical fi le on a storage device. When you read from a fi le, the data is copied into memory. When you write to a fi le, the data is copied from memory to a storage device. When you are done with a fi le, you close it. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 62

Editor's Notes

  1. Source img https://www.vectorstock.com/royalty-free-vector/exercise-pictogram-icon-image-vector-12145514