SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
File Processing
Hardware Model
                             CPU



 Input Devices         Memory (RAM)             Output Devices



To this point we have been using the            Storage Devices
keyboard for input and the screen for output.
 Both of these are temporary.
                                                                 2
Information Processing Cycle

     Input                  Process                  Output
   Raw Data               (Application)            Information


Output from one process can                           Storage
serve as input to another process.
                              Storage is referred to as secondary
                              storage, and it is permanent
                              storage. Data is permanently
                              stored in files.                    3
Input and Output (I/O)
• In the previous programs, we would enter the test
  data and check the results. If it was incorrect, we
  would change the program, run it again, and re-enter
  the data.
• For the sample output, if we didn’t copy it when it
  was displayed, we had to run it again.
• Depending on the application, it may be more
  efficient to capture the raw data the first time it is
  entered and store in a file.
• A program or many different programs can then read
  the file and process the data in different ways.
• We should capture and validate the data at its points
  of origination (ie cash register, payroll clerk).      4
File I/O handled by Classes
• Primitive data types include int, double, char, etc.
• A class is a data type that has data (variables and values)
  as well as functions associated with it.
• The data and functions associated with a class are
  referred to as members of the class.
• Variables declared using a class as the data type are
  called objects.
• We’ll come back to these definitions as we go through an
  example.
• Sequential file processing – processing the records in
  the order they are stored in the file.
                                                       5
Example Scenario
• We have a file named infile.txt
• The file has 2 records with hours and rate.
• We want to process the file by
  – reading the hours and rate
  – calculating gross pay
  – and then saving the results to outfile.txt


                                                 6
infile.txt
40 10.00
50 15.00

• This would be a simple text file.
• The file can be created with Notepad or
  some other text editor.
• Just enter two values separated by
  whitespace and press return at the end
  of each record.
                                            7
fstream
• We have been using #include <iostream> because this
  is where cin and cout are defined.
• We now need to #include <fstream> because this is
  where the commands to do file processing are defined.
• fstream stands for File Stream.
• We can have input and output file streams, which
  are handled by the classes ifstream and ofstream.
• Recall that a stream is a flow characters.
   – cin is an input stream.
   – cout is output stream.


                                                    8
Sample Program
#include <iostream>     // cin and cout
#include <fstream>      // file processing
using namespace std;

void main ( )
{
  int       hours;
  double rate, gross;
  ifstream inFile;      //declares and assigns a
  ofstream outFile;     //variable name to a stream
                                                      9
Open Function
ifstream inFile;

//ifstream is the class (data type)
//inFile is the object (variable)

inFile.open(“infile.txt”);

//open is a function associated with the object inFile
//open has parenthesis like all functions ( )
//The function call to open is preceded by the object
name and dot operator.
//We pass open( ) an argument (external file name).
                                                     10
Internal and External File Names
    ifstream inFile;

    inFile.open(“infile.txt”);

• inFile is the internal file name (object).
• infile.txt is the external file name.
• open connects the internal name to the external file.
• Naming conventions for the external file names vary by
  Operating Systems (OS).
• Internal names must be valid C++ variable names.
• In the open is the only place we see the external name.

                                                     11
Check if Open was Successful
• after calling open ( ), we must
  check if it was successful by using fail().

  if ( inFile.fail() )            //Boolean
  {
       cout << “Error opening input file…”;
       exit (1);                  //<cstdlib>
  }

                                                12
Open outfile.txt
outFile.open(“outfile.txt”);

if ( outFile.fail() )
{
   cout << “Error opening output file…”;
   exit (1);
}

                                           13
Quick Review
void main ( )
{
  int hours;
  double rate, gross;
  ifstream inFile;             outFile.open(“outfile.txt”);
  ofstream outFile;
                               if ( outFile.fail() )
  inFile.open(“infile.txt”);   {
                                     cout << “Error…”;
  if ( inFile.fail() )               exit (1);
  {
        cout << “Error …”;     }
        exit (1);
  }                                                      14
Recall infile.txt?
40 10.00
50 15.00

• Recall that we are processing infile.txt.
• The next slide shows the while loop.
• The two values have been entered separated
  by whitespace and there is carriage return at
  the of each record (also whitespace).
                                              15
Process the file
inFile >> hours >> rate; // read first record
// cin >> hours >> rate; //same extractors
                                                 infile.txt
                                                 40 10.00
while (! inFile.eof() )
                                               50 15.00
{                                              eof
  gross = hours * rate;
  outFile << hours << rate << gross << endl; //write
// cout << hours << rate << gross << endl;

    inFile >> hours >> rate;    //read next record
}
                                                         16
outfile.txt
40 10.00 400.00
50 15.00 750.00

• Assumes decimal formatting was applied.




                                            17
Close Files
  inFile.close( );
  outFile.close( );

• Release files to Operating System (OS).
• Other users may get file locked error.
• Good housekeeping.



                                            18
Outfile.txt
    while vs do-while                  • 10.00 400.00
                                       50 15.00 750.00
inFile >> hours >> rate;               50 15.00 750.00

while (! inFile.eof() )        do
{                              {
                                    inFile >> hours >> rate;
  gross = hours * rate;
                                    gross = hours * rate;
  outFile << hours << rate
                                    outFile << hours << rate
           << gross << endl;                << gross << endl;

    inFile >> hours >> rate;   } while (! inFile.eof() )
}                              //writes last record twice.
                                                             19
Outfile.txt
   Empty infile.txt                    ?? ??.?? ??.??

inFile >> hours >> rate;

while (! inFile.eof() )        do
{                              {
  gross = hours * rate;             inFile >> hours >> rate;
  outFile << hours << rate          gross = hours * rate;
           << gross << endl;        outFile << hours << rate
                                            << gross << endl;
  inFile >> hours >> rate;
}                              } while (! inFile.eof() )
//while will leave outfile     //do-while writes garbage
   empty.                                                   20
Do-while and File Processing
• Do-while processes last record twice.
• Do-while does not handle empty files.
• Use a while loop for file processing.




                                          21
Constructors and Classes
• Classes are defined for other programmers to use.
• When an object is declared using a class, a special
  function called a constructor is automatically
  called.
• Programmers use constructors to initialize
  variables that are members of the class.
• Constructors can also be overloaded to give
  programmers options when declaring objects.

                                                    22
ifstream Constructor Overloaded
• Default constructor takes no parameters.
     ifstream inFile;
     inFile.open(“infile.txt”);
• Overloaded constructor takes parameters.
     ifstream inFile (“infile.txt”);

     Declare object and open file on same line.
     Gives programmer options.
                                             23
Magic Formula
• Magic formula for formatting numbers to two
  digits after the decimal point works with all
  output streams (cout and ofstreams).

cout.setf(ios::fixed)          outFile.setf(ios::fixed)
cout.setf(ios::showpoint)      outFile.setf(ios::showpoint)
cout.precision(2)              outFile.precision(2)

• Note that cout and outfile are objects and setf and
  precision are member functions.

                                                        24
Set Flag
• setf means Set Flag.
• A flag is a term used with variables
  that can have two possible values.
  – On or off, 0 or 1
  – Y or N,    True or false
• showpoint or don’t showpoint.
• Use unsetf to turn off a flag.
  cout.unsetf(ios::showpoint)
                                         25
Right Justification
• To right justify numbers, use
  the flag named right and
  the function named width together.
• Numbers are right justified by default.
• Strings are left justified by default.

  cout.setf(ios::right);
  cout.width(6);

                                            26
Using right and width( )
outFile.setf(ios::right);

outFile.width(4);       //use four spaces
outFile << hours;       //_ _40
outFile.width(6);
outFile << rate;        //_ _40 _10.00

Have to enter four different commands;
 it’s a lot of typing…
                                            27
Manipulator
• Short cut to call a formatting function.

outFile.setf(ios::right);

outFile << setw(4) << hours << setw(6) << rate;

//need #include <iomanip>
                                             28
Formatted I/O
• cin uses formatted input.
• If you cin an integer or double, it knows how to get
  those values.
• If you enter an alpha character for a cin that is
  expecting a number, the program will bomb (try it).
• To control for this, you need to get one character at
  a time and then concatenate all of the values that
  were entered.
• For example, for 10.00, you would get the 1, 0, a
  period, 0, and then another 0.
• If the values were all valid, you would convert these
  characters into a double using some built in
  predefined functions (atof, atoi).                 29
Character I/O Functions
• We actually use some of character I/O functions in
  our displayContinue().
• To get one character including white space use get.
      cin.get(char);
• To get entire line up to the newline use getline.
      cin.getline(char, intSize);
• To put out one character use put.
      cout.put(char);

                                                   30
Functions to Check Value
• After you get one character, you will need
   to check what it is.
isalpha(char) - (a-z)
isdigit(char) - (0-9)
isspace(char) - (whitespace)
isupper(char) – (checks for uppercase)
islower(char) – (checks for lowercase)
                                               31
Functions to Change Value
• These functions can change the case if the
  value in the char variable is an alpha.

  tolower(char)
  toupper (char)

Is the following statement true or false?

  if (islower(tolower(‘A’))) //true or false
                                               32
ASC II Table
• Review the ASCII table available on the website.
• ASCII table shows the binary value of all
  characters.
• The hexadecimal values are also presented because
  when a program aborts and memory contents are
  displayed, the binary values are converted to
  hexadecimal (Hex).
• The Dec column shows the decimal value of the
  binary value.
• Look up CR, HT, Space, A, a
• It shows that the values for a capital A is the same
  as a lowercase a.
• The values also inform us how data will be sorted.
                                                   33
Control Structures Reviewed
•   1st Sequence Control
•   2nd Selection Control (if, if-else)
•   3rd Repetition Control (while, do-while)
•   4th Case Control
    – Also known as Multiway Branching (if-else)
    – Related to Selection Control
• The switch statement is an alternative
  to if-else statements for handling cases.
                                                   34
Switch Example – main()
void main()
{

    char choice;
    do // while (choice != 'D')
    {

        cout << "Enter the letter of the desired menu option. n"
             << "Press the Enter key after entering the letter. n n"
                   << "   A: Add Customer n"
                   << "   B: Up Customer n"
                   << "   C: Delete Customer n"
                   << "   D: Exit Customer Module n n"
                << "Choice: ";
        cin >> choice;                                         35
switch (choice)                 //controlling expression

{
          case ‘a’:


          case 'A':

                      addCustomer();

                      break;

          case 'B':

                      upCustomer();

                      break;

          case 'C':

                      deleteCustomer();

                      break;

          case 'D':

                      cout << "Exiting Customer Module...please wait.nn";   36
Controlling Expression
• The valid types for the controlling expression are
   –   bool
   –   int
   –   char
   –   enum
• Enum is list of constants of the type int
   – Enumeration
   – Enum MONTH_LENGTH { JAN = 31, FEB = 28 …};
   – Considered a data type that is programmer defined.
                                                          37
Switch Statement Summary
• Use the keyword case and the colon to create a
  label.
  – case ‘A’:
  – A Label is a place to branch to.
• Handle each possible case in the body.
• Use the default: label to catch errors.
• Don’t forget the break statement, or else the
  flow will just fall through to next command.
• Compares to an if-else statement.
                                                  38
Break Statement
• The break statement is used to end a sequence
  of statements in a switch statement.
• It can also be used to exit a loop
  (while, do-while, for-loop).
• When the break statement is executed in a
  loop, the loop statement ends immediately
  and execution continues with the statement
  following the loop.
                                            39
Improper Use of Break
• If you have to use the break statement to get
  out of a loop, the loop was probably not
  designed correctly.
• There should be one way in and one way
  out of the loop.
• Avoid using the break statement.


                                              40
Break Example
int loopCnt = 1;
while (true)                //always true
{
   if (loopCnt <= empCnt)   //Boolean is inside the loop
         break;

    getRate()
    getHours()
    calcGross()
    displayDetails()
    loopCnt++;
}

                                                           41
Continue Statement
• The continue statement ends the current
  loop iteration.
• Transfers control to the Boolean expression.
• In a for loop, the statement transfers control
  to the up expression.
• Avoid using the continue statement.


                                               42
Continue Example
int loopCnt = 1;
while (loopCnt <= empCnt)
{

    getRate()
    getHours()
    calcGross()
    if (gross < 0 )         //skip zeros
    {

        loopCnt++
        continue;           //go to top of loop
    }

    displayDetails()
    loopCnt++;
}

                                                  43
Summary
•   File Processing
•   Introduced classes and objects
•   Formatting flags and functions
•   Character I/O and functions
•   ASCII Table
•   Switch Statement

                                     44

Weitere ähnliche Inhalte

Was ist angesagt?

Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelVitaly Nikolenko
 
Unit 4
Unit 4Unit 4
Unit 4siddr
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocationindra Kishor
 
Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1PyCon Italia
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for BioinformaticsJosé Héctor Gálvez
 
Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
Looking Ahead to Tcl 8.6
Looking Ahead to Tcl 8.6Looking Ahead to Tcl 8.6
Looking Ahead to Tcl 8.6ActiveState
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)Subhas Kumar Ghosh
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in CTushar B Kute
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CMahendra Yadav
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overviewgourav kottawar
 
Reliable Windows Heap Exploits
Reliable Windows Heap ExploitsReliable Windows Heap Exploits
Reliable Windows Heap Exploitsamiable_indian
 
File handling in C++
File handling in C++File handling in C++
File handling in C++Hitesh Kumar
 

Was ist angesagt? (20)

Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Unit 4
Unit 4Unit 4
Unit 4
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Operating System Assignment Help
Operating System Assignment HelpOperating System Assignment Help
Operating System Assignment Help
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 
Data file handling
Data file handlingData file handling
Data file handling
 
Systemcall1
Systemcall1Systemcall1
Systemcall1
 
Looking Ahead to Tcl 8.6
Looking Ahead to Tcl 8.6Looking Ahead to Tcl 8.6
Looking Ahead to Tcl 8.6
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File management
File managementFile management
File management
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
Reliable Windows Heap Exploits
Reliable Windows Heap ExploitsReliable Windows Heap Exploits
Reliable Windows Heap Exploits
 
Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 

Andere mochten auch

Fundamental File Processing Operations
Fundamental File Processing OperationsFundamental File Processing Operations
Fundamental File Processing OperationsRico
 
File Processing System
File Processing SystemFile Processing System
File Processing SystemDMMMSU-SLUC
 
File Organization
File OrganizationFile Organization
File OrganizationManyi Man
 
Lecture storage-buffer
Lecture storage-bufferLecture storage-buffer
Lecture storage-bufferKlaas Krona
 
File org leela mdhm 21 batch aiha lecture
File org   leela mdhm 21 batch aiha lectureFile org   leela mdhm 21 batch aiha lecture
File org leela mdhm 21 batch aiha lectureBobba Leeladhar
 
Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)
Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)
Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)Beat Signer
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File ProcessingRanel Padon
 
Tries - Tree Based Structures for Strings
Tries - Tree Based Structures for StringsTries - Tree Based Structures for Strings
Tries - Tree Based Structures for StringsAmrinder Arora
 
Disadvantages of file management system (file processing systems)
Disadvantages of file management system(file processing systems)Disadvantages of file management system(file processing systems)
Disadvantages of file management system (file processing systems) raj upadhyay
 
File access methods.54
File access methods.54File access methods.54
File access methods.54myrajendra
 
Fundamental concepts in linguistics
Fundamental concepts in linguisticsFundamental concepts in linguistics
Fundamental concepts in linguisticsamna-shahid
 
CS3270 - DATABASE SYSTEM - Lecture (2)
CS3270 - DATABASE SYSTEM - Lecture (2)CS3270 - DATABASE SYSTEM - Lecture (2)
CS3270 - DATABASE SYSTEM - Lecture (2)Dilawar Khan
 

Andere mochten auch (20)

Fundamental File Processing Operations
Fundamental File Processing OperationsFundamental File Processing Operations
Fundamental File Processing Operations
 
File Processing System
File Processing SystemFile Processing System
File Processing System
 
File Organization
File OrganizationFile Organization
File Organization
 
File structures
File structuresFile structures
File structures
 
Lecture storage-buffer
Lecture storage-bufferLecture storage-buffer
Lecture storage-buffer
 
File org leela mdhm 21 batch aiha lecture
File org   leela mdhm 21 batch aiha lectureFile org   leela mdhm 21 batch aiha lecture
File org leela mdhm 21 batch aiha lecture
 
Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)
Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)
Access Methods - Lecture 9 - Introduction to Databases (1007156ANR)
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File Processing
 
Tries - Tree Based Structures for Strings
Tries - Tree Based Structures for StringsTries - Tree Based Structures for Strings
Tries - Tree Based Structures for Strings
 
Digital Search Tree
Digital Search TreeDigital Search Tree
Digital Search Tree
 
Disadvantages of file management system (file processing systems)
Disadvantages of file management system(file processing systems)Disadvantages of file management system(file processing systems)
Disadvantages of file management system (file processing systems)
 
File organization
File organizationFile organization
File organization
 
Trie Data Structure
Trie Data StructureTrie Data Structure
Trie Data Structure
 
File access methods.54
File access methods.54File access methods.54
File access methods.54
 
File organisation
File organisationFile organisation
File organisation
 
Files Vs DataBase
Files Vs DataBaseFiles Vs DataBase
Files Vs DataBase
 
File Management
File ManagementFile Management
File Management
 
Fundamental concepts in linguistics
Fundamental concepts in linguisticsFundamental concepts in linguistics
Fundamental concepts in linguistics
 
CS3270 - DATABASE SYSTEM - Lecture (2)
CS3270 - DATABASE SYSTEM - Lecture (2)CS3270 - DATABASE SYSTEM - Lecture (2)
CS3270 - DATABASE SYSTEM - Lecture (2)
 
File management
File managementFile management
File management
 

Ähnlich wie 06 file processing

Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O YourHelper1
 
Linux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/OLinux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/OYourHelper1
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesHelpWithAssignment.com
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxRutujaTandalwade
 
Write a program in C or C++ which simulates CPU scheduling in an opera.pdf
Write a program in C or C++ which simulates CPU scheduling in an opera.pdfWrite a program in C or C++ which simulates CPU scheduling in an opera.pdf
Write a program in C or C++ which simulates CPU scheduling in an opera.pdfsravi07
 

Ähnlich wie 06 file processing (20)

OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Data file handling
Data file handlingData file handling
Data file handling
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
Linux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/OLinux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/O
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
File mangement
File mangementFile mangement
File mangement
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
 
File Handling in C .pptx
File Handling in C .pptxFile Handling in C .pptx
File Handling in C .pptx
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
 
Write a program in C or C++ which simulates CPU scheduling in an opera.pdf
Write a program in C or C++ which simulates CPU scheduling in an opera.pdfWrite a program in C or C++ which simulates CPU scheduling in an opera.pdf
Write a program in C or C++ which simulates CPU scheduling in an opera.pdf
 
A Peek into TFRT
A Peek into TFRTA Peek into TFRT
A Peek into TFRT
 
Java sockets
Java socketsJava sockets
Java sockets
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 

Kürzlich hochgeladen

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 

Kürzlich hochgeladen (20)

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 

06 file processing

  • 2. Hardware Model CPU Input Devices Memory (RAM) Output Devices To this point we have been using the Storage Devices keyboard for input and the screen for output. Both of these are temporary. 2
  • 3. Information Processing Cycle Input Process Output Raw Data (Application) Information Output from one process can Storage serve as input to another process. Storage is referred to as secondary storage, and it is permanent storage. Data is permanently stored in files. 3
  • 4. Input and Output (I/O) • In the previous programs, we would enter the test data and check the results. If it was incorrect, we would change the program, run it again, and re-enter the data. • For the sample output, if we didn’t copy it when it was displayed, we had to run it again. • Depending on the application, it may be more efficient to capture the raw data the first time it is entered and store in a file. • A program or many different programs can then read the file and process the data in different ways. • We should capture and validate the data at its points of origination (ie cash register, payroll clerk). 4
  • 5. File I/O handled by Classes • Primitive data types include int, double, char, etc. • A class is a data type that has data (variables and values) as well as functions associated with it. • The data and functions associated with a class are referred to as members of the class. • Variables declared using a class as the data type are called objects. • We’ll come back to these definitions as we go through an example. • Sequential file processing – processing the records in the order they are stored in the file. 5
  • 6. Example Scenario • We have a file named infile.txt • The file has 2 records with hours and rate. • We want to process the file by – reading the hours and rate – calculating gross pay – and then saving the results to outfile.txt 6
  • 7. infile.txt 40 10.00 50 15.00 • This would be a simple text file. • The file can be created with Notepad or some other text editor. • Just enter two values separated by whitespace and press return at the end of each record. 7
  • 8. fstream • We have been using #include <iostream> because this is where cin and cout are defined. • We now need to #include <fstream> because this is where the commands to do file processing are defined. • fstream stands for File Stream. • We can have input and output file streams, which are handled by the classes ifstream and ofstream. • Recall that a stream is a flow characters. – cin is an input stream. – cout is output stream. 8
  • 9. Sample Program #include <iostream> // cin and cout #include <fstream> // file processing using namespace std; void main ( ) { int hours; double rate, gross; ifstream inFile; //declares and assigns a ofstream outFile; //variable name to a stream 9
  • 10. Open Function ifstream inFile; //ifstream is the class (data type) //inFile is the object (variable) inFile.open(“infile.txt”); //open is a function associated with the object inFile //open has parenthesis like all functions ( ) //The function call to open is preceded by the object name and dot operator. //We pass open( ) an argument (external file name). 10
  • 11. Internal and External File Names ifstream inFile; inFile.open(“infile.txt”); • inFile is the internal file name (object). • infile.txt is the external file name. • open connects the internal name to the external file. • Naming conventions for the external file names vary by Operating Systems (OS). • Internal names must be valid C++ variable names. • In the open is the only place we see the external name. 11
  • 12. Check if Open was Successful • after calling open ( ), we must check if it was successful by using fail(). if ( inFile.fail() ) //Boolean { cout << “Error opening input file…”; exit (1); //<cstdlib> } 12
  • 13. Open outfile.txt outFile.open(“outfile.txt”); if ( outFile.fail() ) { cout << “Error opening output file…”; exit (1); } 13
  • 14. Quick Review void main ( ) { int hours; double rate, gross; ifstream inFile; outFile.open(“outfile.txt”); ofstream outFile; if ( outFile.fail() ) inFile.open(“infile.txt”); { cout << “Error…”; if ( inFile.fail() ) exit (1); { cout << “Error …”; } exit (1); } 14
  • 15. Recall infile.txt? 40 10.00 50 15.00 • Recall that we are processing infile.txt. • The next slide shows the while loop. • The two values have been entered separated by whitespace and there is carriage return at the of each record (also whitespace). 15
  • 16. Process the file inFile >> hours >> rate; // read first record // cin >> hours >> rate; //same extractors infile.txt 40 10.00 while (! inFile.eof() ) 50 15.00 { eof gross = hours * rate; outFile << hours << rate << gross << endl; //write // cout << hours << rate << gross << endl; inFile >> hours >> rate; //read next record } 16
  • 17. outfile.txt 40 10.00 400.00 50 15.00 750.00 • Assumes decimal formatting was applied. 17
  • 18. Close Files inFile.close( ); outFile.close( ); • Release files to Operating System (OS). • Other users may get file locked error. • Good housekeeping. 18
  • 19. Outfile.txt while vs do-while • 10.00 400.00 50 15.00 750.00 inFile >> hours >> rate; 50 15.00 750.00 while (! inFile.eof() ) do { { inFile >> hours >> rate; gross = hours * rate; gross = hours * rate; outFile << hours << rate outFile << hours << rate << gross << endl; << gross << endl; inFile >> hours >> rate; } while (! inFile.eof() ) } //writes last record twice. 19
  • 20. Outfile.txt Empty infile.txt ?? ??.?? ??.?? inFile >> hours >> rate; while (! inFile.eof() ) do { { gross = hours * rate; inFile >> hours >> rate; outFile << hours << rate gross = hours * rate; << gross << endl; outFile << hours << rate << gross << endl; inFile >> hours >> rate; } } while (! inFile.eof() ) //while will leave outfile //do-while writes garbage empty. 20
  • 21. Do-while and File Processing • Do-while processes last record twice. • Do-while does not handle empty files. • Use a while loop for file processing. 21
  • 22. Constructors and Classes • Classes are defined for other programmers to use. • When an object is declared using a class, a special function called a constructor is automatically called. • Programmers use constructors to initialize variables that are members of the class. • Constructors can also be overloaded to give programmers options when declaring objects. 22
  • 23. ifstream Constructor Overloaded • Default constructor takes no parameters. ifstream inFile; inFile.open(“infile.txt”); • Overloaded constructor takes parameters. ifstream inFile (“infile.txt”); Declare object and open file on same line. Gives programmer options. 23
  • 24. Magic Formula • Magic formula for formatting numbers to two digits after the decimal point works with all output streams (cout and ofstreams). cout.setf(ios::fixed) outFile.setf(ios::fixed) cout.setf(ios::showpoint) outFile.setf(ios::showpoint) cout.precision(2) outFile.precision(2) • Note that cout and outfile are objects and setf and precision are member functions. 24
  • 25. Set Flag • setf means Set Flag. • A flag is a term used with variables that can have two possible values. – On or off, 0 or 1 – Y or N, True or false • showpoint or don’t showpoint. • Use unsetf to turn off a flag. cout.unsetf(ios::showpoint) 25
  • 26. Right Justification • To right justify numbers, use the flag named right and the function named width together. • Numbers are right justified by default. • Strings are left justified by default. cout.setf(ios::right); cout.width(6); 26
  • 27. Using right and width( ) outFile.setf(ios::right); outFile.width(4); //use four spaces outFile << hours; //_ _40 outFile.width(6); outFile << rate; //_ _40 _10.00 Have to enter four different commands; it’s a lot of typing… 27
  • 28. Manipulator • Short cut to call a formatting function. outFile.setf(ios::right); outFile << setw(4) << hours << setw(6) << rate; //need #include <iomanip> 28
  • 29. Formatted I/O • cin uses formatted input. • If you cin an integer or double, it knows how to get those values. • If you enter an alpha character for a cin that is expecting a number, the program will bomb (try it). • To control for this, you need to get one character at a time and then concatenate all of the values that were entered. • For example, for 10.00, you would get the 1, 0, a period, 0, and then another 0. • If the values were all valid, you would convert these characters into a double using some built in predefined functions (atof, atoi). 29
  • 30. Character I/O Functions • We actually use some of character I/O functions in our displayContinue(). • To get one character including white space use get. cin.get(char); • To get entire line up to the newline use getline. cin.getline(char, intSize); • To put out one character use put. cout.put(char); 30
  • 31. Functions to Check Value • After you get one character, you will need to check what it is. isalpha(char) - (a-z) isdigit(char) - (0-9) isspace(char) - (whitespace) isupper(char) – (checks for uppercase) islower(char) – (checks for lowercase) 31
  • 32. Functions to Change Value • These functions can change the case if the value in the char variable is an alpha. tolower(char) toupper (char) Is the following statement true or false? if (islower(tolower(‘A’))) //true or false 32
  • 33. ASC II Table • Review the ASCII table available on the website. • ASCII table shows the binary value of all characters. • The hexadecimal values are also presented because when a program aborts and memory contents are displayed, the binary values are converted to hexadecimal (Hex). • The Dec column shows the decimal value of the binary value. • Look up CR, HT, Space, A, a • It shows that the values for a capital A is the same as a lowercase a. • The values also inform us how data will be sorted. 33
  • 34. Control Structures Reviewed • 1st Sequence Control • 2nd Selection Control (if, if-else) • 3rd Repetition Control (while, do-while) • 4th Case Control – Also known as Multiway Branching (if-else) – Related to Selection Control • The switch statement is an alternative to if-else statements for handling cases. 34
  • 35. Switch Example – main() void main() { char choice; do // while (choice != 'D') { cout << "Enter the letter of the desired menu option. n" << "Press the Enter key after entering the letter. n n" << " A: Add Customer n" << " B: Up Customer n" << " C: Delete Customer n" << " D: Exit Customer Module n n" << "Choice: "; cin >> choice; 35
  • 36. switch (choice) //controlling expression { case ‘a’: case 'A': addCustomer(); break; case 'B': upCustomer(); break; case 'C': deleteCustomer(); break; case 'D': cout << "Exiting Customer Module...please wait.nn"; 36
  • 37. Controlling Expression • The valid types for the controlling expression are – bool – int – char – enum • Enum is list of constants of the type int – Enumeration – Enum MONTH_LENGTH { JAN = 31, FEB = 28 …}; – Considered a data type that is programmer defined. 37
  • 38. Switch Statement Summary • Use the keyword case and the colon to create a label. – case ‘A’: – A Label is a place to branch to. • Handle each possible case in the body. • Use the default: label to catch errors. • Don’t forget the break statement, or else the flow will just fall through to next command. • Compares to an if-else statement. 38
  • 39. Break Statement • The break statement is used to end a sequence of statements in a switch statement. • It can also be used to exit a loop (while, do-while, for-loop). • When the break statement is executed in a loop, the loop statement ends immediately and execution continues with the statement following the loop. 39
  • 40. Improper Use of Break • If you have to use the break statement to get out of a loop, the loop was probably not designed correctly. • There should be one way in and one way out of the loop. • Avoid using the break statement. 40
  • 41. Break Example int loopCnt = 1; while (true) //always true { if (loopCnt <= empCnt) //Boolean is inside the loop break; getRate() getHours() calcGross() displayDetails() loopCnt++; } 41
  • 42. Continue Statement • The continue statement ends the current loop iteration. • Transfers control to the Boolean expression. • In a for loop, the statement transfers control to the up expression. • Avoid using the continue statement. 42
  • 43. Continue Example int loopCnt = 1; while (loopCnt <= empCnt) { getRate() getHours() calcGross() if (gross < 0 ) //skip zeros { loopCnt++ continue; //go to top of loop } displayDetails() loopCnt++; } 43
  • 44. Summary • File Processing • Introduced classes and objects • Formatting flags and functions • Character I/O and functions • ASCII Table • Switch Statement 44