GE 211 Programming in C ++ Dr. Ahmed Telba Room :Ac -134

Slides:



Advertisements
Similar presentations
C++ Basics Prof. Shermane Austin. Learning Programming Language Basics Data Types – simple Expressions Relational and Logical Operators Conditional Statements.
Advertisements

計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
Chapter 2: Introduction to C++.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Admin Office hours 2:45-3:15 today due to department meeting if you change addresses during the semester, please unsubscribe the old one from the.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output.
File input and output in C++ Dr. Ahmed Telba. CSE202: Lecture 9The Ohio State University2 Reading & Writing to Files.
Darbas su failais Arnas Terekas IT 1gr. Vilniaus universitetas Matematikos ir informatikos fakultetas.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
C++ Programming: Basic Elements of C++.
File I/O ifstreams and ofstreams Sections 11.1 &
Programming Principles II Lecture Notes 7 Files Andreas Savva.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Lecture #6 OPERATORS AND ITS TYPES By Shahid Naseem (Lecturer)
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
I/O in C++ October 7, Junaed Sattar. Stream I/O a stream is a flow of bytes/characters/ints or any type of data input streams: to the program output.
File I/O in C++ II. Open() function Open() is a member function in each classes ( fstream, ifstream, ofstream) Void fstream :: open ( const char *filename,
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
C++ Programming: chapter 6 – iostream 2014, Spring Pusan National University Ki-Joune Li 1.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
C++ Programming: chapter 6 – iostream 2015, Spring Pusan National University Ki-Joune Li 1.
Lecture 14 Arguments, Classes and Files. Arguments.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Files To read a file – We must know its name – We must open it (for reading) – Then we can read – Then we must close it That is typically done implicitly.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Basic file operations in C++ Dr. Ahmed Telba 1. 2 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
CS212: Object Oriented Analysis and Design
Chapter 1.2 Introduction to C++ Programming
What is wrong in the following function definition
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
File Processing in C++ Data is stored in files so that it may be retrieved for processing when needed.
Chapter 1.2 Introduction to C++ Programming
Basic file operations in C++
Lecture 9 Files, Pointers
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Basic Input and Output Operations
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
2.1 Parts of a C++ Program.
آشنایی با ساختارها و کار با فایلها
Today’s Lecture I/O Streams Tools for File I/O
File Processing in C++ Data is stored in files so that it may be retrieved for processing when needed.
Chapter 3 Input output.
Chapter 2: Introduction to C++.
C++ Programming: chapter 6 – iostream
What Actions Do We Have Part 1
Chapter 1 c++ structure C++ Input / Output
Text Files.
Presentation transcript:

GE 211 Programming in C ++ Dr. Ahmed Telba Room :Ac

Input/Output with files C++ provides the following classes to perform output and input of characters to/from files: ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files.

Classes in C++ These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files.

Write in file example: // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); system("pause"); return 0; }

open a file The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

WRITING TO FILE

Open file

// writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; }

reading a text file // Data input from a file can also be performed in the same way that we did with cin: #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; }

Input- Output with files // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } [file example.txt] Writing this to a file.

Open a file The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

ios::inOpen for input operations. ios::outOpen for output operations. ios::binaryOpen in binary mode. ios::ateSet the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file. ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations. ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

Classes for file

writing on a text file #include // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } [file example.txt] This is a line. This is another line.

/ reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; } This is a line. This is another line.

obtaining file size // obtaining file size #include #include size is: 40 bytes. using namespace std; int main () { long begin,end; ifstream myfile ("example.txt"); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0; }

Binary files In binary files, to input and output data with the extraction and insertion operators ( >) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...). File streams include two member functions specifically designed to input and output binary data sequentially: write and read. The first one (write) is a member function of ostream inherited by ofstream. And read is a member function of istream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are: write ( memory_block, size ); read ( memory_block, size ); Where memory_block is of type "pointer to char" (char*), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.

// reading a complete binary file #include using namespace std; the complete file content is in memory ifstream::pos_type size; char * memblock; int main () { ifstream file ("example.bin", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); cout << "the complete file content is in memory"; delete[] memblock; } else cout << "Unable to open file"; return 0; }

Declaration of variables In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specified of the desired data type (like int, bool, float...) followed by a valid variable identifier. For example: int a; float mynumber; int a, b, c; int a; int b; int c;

// operating with variables #include using namespace std; int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0; }

\nnewline\rcarriage return\ttab\vvertical tab\bbackspace\fform feed (page feed)\aalert (beep)\'single quote (')\"double quote (")\?question mark (?)\\backslash (\)

// defined constants: calculate circumference #include using namespace std; #define PI #define NEWLINE '\n' int main () { double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0; }

#include using namespace std; int main () { // input variables double a; double b; double c; // result variables double desc; double root1; double root2; double iroot; // prompt and input the user's coefficients for a, b and c cout << "Quadratic Equation Root Solver Program\n\n"; cout << "Enter the quadratic equation's coefficients a, b and c\n" << "separated by a blank\n"; cin >> a >> b >> c; // setup floating point format for output of roots cout << fixed << setprecision (4) << endl; // check for division by 0 or not a quadratic case if (fabs (a) < ) { cout << "Since a is zero, there is no solution - not a quadratic\n"; } // here it is a quadratic equation, sort out roots else { desc = b * b - 4 * a * c; // is the desc basically 0 indicating multiple roots at one value? if (fabs (desc) <= ) { root1 = - b / (2 * a); cout << "Multiple roots at " << setw (12) << root1 << endl; }

// is the desc positive indicating two real roots else if (desc > 0) { root1 = (-b + sqrt (desc)) / (2 * a); root2 = (-b - sqrt (desc)) / (2 * a); cout << "Two real roots at: " << setw (12) << root1 << endl; cout << " " << setw (12) << root2 << endl; } // desc is negative indicating two imaginary roots else { desc = fabs (desc); root1 = -b / (2 * a); iroot = sqrt (desc) / (2 * a); cout << "Two imaginary roots at :" << setw (12) << root1 << " + i * " << setw (12) << iroot << endl; cout << " " << setw (12) << root1 << " - i * " << setw (12) << iroot << endl; } return 0; }

Assignment operator #include using namespace std; int main () { int a, b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a = b; // a:4, b:4 b = 7; // a:4, b:7 cout << "a:"; cout << a; cout << " b:"; cout << b; return 0; }

Expression in C++ a = 2 + (b = 5); is equivalent to: b = 5; a = 2 + b; The following expression is also valid in C++: a = b = c = 5;

Arithmetic operators ( +, -, *, /, % ) The five arithmetical operations supported by the C++ language are: +addition -subtraction *multiplication /division %modulo Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

#include using namespace std; int main () { int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; }

Input- Output with files // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } [file example.txt] Writing this to a file.

Open a file The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

ios::inOpen for input operations. ios::outOpen for output operations. ios::binaryOpen in binary mode. ios::ateSet the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file. ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations. ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

Classes for file

writing on a text file #include // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } [file example.txt] This is a line. This is another line.

/ reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; } This is a line. This is another line.

obtaining file size // obtaining file size #include #include size is: 40 bytes. using namespace std; int main () { long begin,end; ifstream myfile ("example.txt"); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0; }

Binary files In binary files, to input and output data with the extraction and insertion operators ( >) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...). File streams include two member functions specifically designed to input and output binary data sequentially: write and read. The first one (write) is a member function of ostream inherited by ofstream. And read is a member function of istream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are: write ( memory_block, size ); read ( memory_block, size ); Where memory_block is of type "pointer to char" (char*), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.

// reading a complete binary file #include using namespace std; the complete file content is in memory ifstream::pos_type size; char * memblock; int main () { ifstream file ("example.bin", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); cout << "the complete file content is in memory"; delete[] memblock; } else cout << "Unable to open file"; return 0; }

#include using namespace std; const double PI = acos (-1.); int main () { double V; // initial volts of AC power supply double Z; // initial impedance of load double angle; // initial angle of impedance of load double I; // current flow in amperes double radAngle; // angle in radians double P; // real power in watts double R; // reactive power in VAR double A; // apparant power in VA double PF; // power factor // prompt and input the initial values of V, Z and angle cout << "Enter the AC power supply voltage: "; cin >> V; cout << "Enter the impedance of the load in ohms: "; cin >> Z; cout << "Enter the angle in degrees: ";

cin >> angle; // calculate intermediate needed values radAngle = angle * PI / 180; I = V / Z; // calculate the four resulting power factors P = V * I * cos (radAngle); R = V * I * sin (radAngle); A = V * I; PF = cos (radAngle); // setup floating point format for output cout << fixed << setprecision (3); // echo print the input cout << "\n Power Supplied to a Load Results\n"; cout << "AC voltage supplied: " << setw(8) << V << " volts\n"; cout << "Load impedance of: " << setw(8) << Z << " ohms\n"; cout << " at an angle of: " << setw(8) << angle << " degrees\n"; cout << "Yields these power factors\n"; cout << "Real power supplied: " << setw(8) << P << " watts\n"; cout << "Reactive power supplied: " << setw(8) << R << " volt-amperes-reactive\n"; cout << "Apparant power supplied: " << setw(8) << A << " volt-amperes\n"; cout << "Power factor is: " << setw(8) << PF << endl; system("PAUSE"); return 0; }