Unit 5_Part 2 CSE2001 IOSTREAMS and Files OOPs using C++
In this Unit 5 we discussed the following topics,
UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from files
5.6 binary files
Basics of files and its functions with exampleSunil Patel
The document discusses input/output files in C++. It covers key concepts like streams, predefined console streams, file modes, and file pointers. Binary file operations like get(), put(), read(), write(), and flush() are also summarized for reading and writing bytes from files. The main steps for file I/O in C++ are to declare a file name variable, associate it with a disk file, open the file, use the file for input/output, and close the file.
This document discusses file management functions in C++. It introduces file streams/file handling using the <fstream> header file. The header file supports ofstream for writing, ifstream for reading, and fstream for both. Common file operations include creating/opening a file using open(), reading data with read(), writing with write(), and closing a file with close(). The document provides examples of opening files for writing, reading, appending, and truncating and using extraction and insertion operators to read from and write to files.
This document provides an overview of Java I/O including different types of I/O, how Java supports I/O through streams and classes like File, serialization, compression, Console, and Properties. It discusses byte and character streams, buffered streams, reading/writing files, and preferences. Key points are that Java I/O uses streams as an abstraction, byte streams operate on bytes while character streams use characters, and buffered streams improve efficiency by buffering reads/writes.
Introduction to C Language - Version 1.0 by Mark John LadoMark John Lado, MIT
The C programming language is a general-purpose, high – level language (generally denoted as structured language). C programming language was at first developed by Dennis M. Ritchie at At&T Bell Labs.
C is one of the most commonly used programming languages. It is simple and efficient therefore it becomes best among all. It is used in all extents of application, mainly in the software development.
Many software's & applications as well as the compilers for the other programming languages are written in C also Operating Systems like Unix, DOS and windows are written in C.
C has many powers, it is simple, stretchy and portable, and it can control system hardware easily. It is also one of the few languages to have an international standard, ANSI C.
The document describes the structure of a C++ program. It is divided into several key sections: documentation, link, namespaces, global definitions, main program, and subprograms. The main program section contains the main function which is called when the program executes. Subprogram sections contain user-defined functions. The document also discusses preprocessing directives, macros, file inclusion and other elements that make up the overall structure of a C++ program.
Files allow programs to permanently store data. A file contains records, which are collections of related data items called fields. There are different types of files depending on how the records are ordered, such as ascending order by key field. C++ uses streams for input and output, including ifstream for input files and ofstream for output files. Objects can also be written to and read from files to create persistent objects that remember their data between runs of a program.
The document discusses file handling in C++. It explains that files store data permanently on storage devices and can be opened for input or output by programs. Streams act as an interface between files and programs, representing the flow of data. The predefined stream classes like ifstream, ofstream, and fstream allow reading from and writing to files. The document outlines the general steps to work with files, describes file modes and pointers, and provides examples of reading from and writing to both text and binary files in C++.
Excellence Technology is one of the top ISO satisfied company in Chandigarh and Mohali . We provide Best industrial training Digital marketing, PHP.java, best web designing training ,software testing ,Python Course In Chandigarh etc . It can be provided 6 month and 28 days industrial training & tuition classes.
Basics of files and its functions with exampleSunil Patel
The document discusses input/output files in C++. It covers key concepts like streams, predefined console streams, file modes, and file pointers. Binary file operations like get(), put(), read(), write(), and flush() are also summarized for reading and writing bytes from files. The main steps for file I/O in C++ are to declare a file name variable, associate it with a disk file, open the file, use the file for input/output, and close the file.
This document discusses file management functions in C++. It introduces file streams/file handling using the <fstream> header file. The header file supports ofstream for writing, ifstream for reading, and fstream for both. Common file operations include creating/opening a file using open(), reading data with read(), writing with write(), and closing a file with close(). The document provides examples of opening files for writing, reading, appending, and truncating and using extraction and insertion operators to read from and write to files.
This document provides an overview of Java I/O including different types of I/O, how Java supports I/O through streams and classes like File, serialization, compression, Console, and Properties. It discusses byte and character streams, buffered streams, reading/writing files, and preferences. Key points are that Java I/O uses streams as an abstraction, byte streams operate on bytes while character streams use characters, and buffered streams improve efficiency by buffering reads/writes.
Introduction to C Language - Version 1.0 by Mark John LadoMark John Lado, MIT
The C programming language is a general-purpose, high – level language (generally denoted as structured language). C programming language was at first developed by Dennis M. Ritchie at At&T Bell Labs.
C is one of the most commonly used programming languages. It is simple and efficient therefore it becomes best among all. It is used in all extents of application, mainly in the software development.
Many software's & applications as well as the compilers for the other programming languages are written in C also Operating Systems like Unix, DOS and windows are written in C.
C has many powers, it is simple, stretchy and portable, and it can control system hardware easily. It is also one of the few languages to have an international standard, ANSI C.
The document describes the structure of a C++ program. It is divided into several key sections: documentation, link, namespaces, global definitions, main program, and subprograms. The main program section contains the main function which is called when the program executes. Subprogram sections contain user-defined functions. The document also discusses preprocessing directives, macros, file inclusion and other elements that make up the overall structure of a C++ program.
Files allow programs to permanently store data. A file contains records, which are collections of related data items called fields. There are different types of files depending on how the records are ordered, such as ascending order by key field. C++ uses streams for input and output, including ifstream for input files and ofstream for output files. Objects can also be written to and read from files to create persistent objects that remember their data between runs of a program.
The document discusses file handling in C++. It explains that files store data permanently on storage devices and can be opened for input or output by programs. Streams act as an interface between files and programs, representing the flow of data. The predefined stream classes like ifstream, ofstream, and fstream allow reading from and writing to files. The document outlines the general steps to work with files, describes file modes and pointers, and provides examples of reading from and writing to both text and binary files in C++.
Excellence Technology is one of the top ISO satisfied company in Chandigarh and Mohali . We provide Best industrial training Digital marketing, PHP.java, best web designing training ,software testing ,Python Course In Chandigarh etc . It can be provided 6 month and 28 days industrial training & tuition classes.
The document discusses the instruction set of the 8085 microprocessor. It states that the 8085 has 246 instructions that are each represented by an 8-bit binary value called the op-code or instruction byte. It also mentions that an instruction is a binary pattern inside a microprocessor that performs a specific function, and the complete set of instructions a microprocessor supports is called its instruction set.
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...Codemotion
This document discusses extended differential fuzzing techniques. It begins with an overview of common fuzzing and differential fuzzing. Extended differential fuzzing aims to detect more vulnerability types by analyzing outputs across different implementations, inputs, versions, and operating systems. These include path disclosure, user disclosure, error disclosure, code evaluation, command execution, network connections, and file reads. The document demonstrates examples of detecting these behaviors in PHP, Perl, Python and other languages. It promotes an open source fuzzing framework called XDiFF that automates extended differential analysis.
This document discusses low-level input/output in C programming. It explains that low-level I/O provides direct access to files and devices using functions like open(), close(), read(), write(), and lseek(). These functions take a file descriptor as a parameter and allow accessing files sequentially or randomly. The document also covers error handling using errno values and differentiates between high-level and low-level I/O.
This document discusses C++ streams and stream classes. It explains that streams represent the flow of data in C++ programs and are controlled using classes. The key classes are istream for input, ostream for output, and fstream for file input/output. It provides examples of reading from and writing to files using fstream, and describes various stream manipulators like endl. The document also discusses the filebuf and streambuf base classes that perform low-level input/output operations.
This document discusses C++ stream classes and file input/output. It covers ios class functions and flags, manipulators, and user-defined output functions that format console I/O. It also discusses opening and reading/writing to files using ifstream, ofstream and fstream classes. Functions like get(), put(), read(), write(), seekg(), seekp(), tellg(), and tellp() are used to manipulate file pointers and perform I/O on files. Exceptions while accessing files and using command line arguments are also covered.
This document provides an overview of key concepts in C and C++ including:
1. The structure of a C/C++ program including main functions, declarations, statements, and preprocessor directives.
2. Basic data types like integers, floats, characters, and aggregates like arrays and structures.
3. Common programming constructs like selection, loops, functions and input/output.
4. Additional C++ topics like classes, inheritance and input/output streams.
5. Pointers and how they store the address of a variable in memory rather than the variable's value.
This document covers lecture 3 of a computer programming course. The lecture objectives are to understand why programmers use functions, how to define functions in Python, function calls and parameter passing. The document explains what functions are, benefits of using functions like simpler code, code reuse and better testing. It provides examples of defining functions, calling functions, using local variables within functions and passing arguments to functions. Exercises are included to demonstrate these concepts.
The document provides information about various Python concepts like PEP 8, pickling, lambda functions, generators, modules, packages and more. It also includes questions about memory management in Python, tools for static analysis, decorators, iterators, slicing, and other common Python interview questions.
The document discusses file handling in C++. It covers:
1) Using input/output files by opening, reading from, and writing to files. Files are interpreted as sequences of bytes and can be text or binary.
2) General file I/O steps which include declaring a file name variable, associating it with a disk file, opening the file, using it, and closing it.
3) Predefined console streams like cin, cout, cerr, and clog which are used for standard input, output, error output, and buffered error output respectively.
The document discusses file handling in C++. It covers:
1) Using input/output files by opening, reading from, and writing to files using streams. Streams act as an interface between files and programs.
2) General file I/O steps which include declaring a file name variable, associating it with a disk file, opening the file, using it, and closing it.
3) Predefined console streams like cin, cout, cerr, and clog which are opened automatically and connected to the keyboard, display, and error output respectively.
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
This document discusses file handling in C++. It defines a file as a collection of stored information, usually on a computer's disk. The main classes for file input/output in C++ are fstream, ifstream, and ofstream. It describes different file operations like opening, closing, reading from and writing to files. It also covers checking for the end of a file and different file opening modes. The two main types of files are text files, which are human-readable, and binary files, which store whole records at once in a non-readable format.
This document provides an overview of the Python programming language in 7 sentences or less:
The document outlines why Python is useful, how to run Python code, basic data types and operators in Python, statements and functions, and some useful Python packages and resources. It discusses that Python is an easy to learn, powerful, and portable programming language that supports object-oriented programming and is free and open source. The document also provides examples of running Python code directly from the interpreter and from script files.
The document discusses input/output files in Java. It covers the key classes used for reading and writing files in Java, including FileInputStream, FileOutputStream, FileReader, and FileWriter. It also discusses byte streams versus character streams, and provides examples of reading and writing to files in Java using these classes. Standard input/output streams like System.in and System.out are also covered.
This document provides an introduction to C++ programming. It begins with definitions of a computer, programming, and the C++ programming process. It then discusses hardware components like the CPU, memory, and input/output devices. It also covers software components like programming languages, operating systems, and the C++ development process. The document provides examples of C++ code and explanations of language features like variables, operators, and data types. It concludes with an overview of getting started with C++ input/output functions.
The type of a value refers to the kind of data it represents. In Python, the main types are:
- int - integer numbers like 1, 2, 100
- float - floating point numbers like 1.5, 3.14159
- str - strings, sequences of characters like 'hello'
- bool - boolean values True or False
When you write code, Python assigns a type to each value. The type determines how it can be used and what operations are valid on it. For example, you can add two integers but not add an integer to a string. Checking and understanding types is important for writing correct Python code.
The document discusses linkers and loaders, describing their functions in combining object files into executable files. It covers the ELF format, static vs dynamic linking, and how executable files are run using static or dynamic linkers. Key points include how static linkers resolve symbols and perform relocation, while dynamic linkers use shared libraries and handle relocation at runtime via the dynamic linker.
1. The document discusses object oriented programming concepts like classes, objects, inheritance, and polymorphism in C++.
2. It begins with an introduction to procedural programming and its limitations. Object oriented programming aims to overcome these limitations by emphasizing data over procedures and allowing for inheritance, polymorphism, and encapsulation.
3. The document then covers key OOP concepts like classes, objects, constructors, and static class members in C++. It provides examples of creating classes and objects.
This document provides information about file handling in C++. It discusses key concepts like input/output streams, opening and closing files, and different file types. Specifically, it covers:
- The different stream classes like fstream, ifstream, and ofstream that are used for file input/output.
- Opening and closing files using functions like open() and close(), and specifying open modes like ios::out.
- The two main types of files - text files that use character translations and binary files that store raw bytes.
- Basic file operations in C++ like reading, writing, and manipulating files using functions like read(), write(), seekp() etc.
- Examples of opening
Null Bangalore | Pentesters Approach to AWS IAMDivyanshu
#Abstract:
- Learn more about the real-world methods for auditing AWS IAM (Identity and Access Management) as a pentester. So let us proceed with a brief discussion of IAM as well as some typical misconfigurations and their potential exploits in order to reinforce the understanding of IAM security best practices.
- Gain actionable insights into AWS IAM policies and roles, using hands on approach.
#Prerequisites:
- Basic understanding of AWS services and architecture
- Familiarity with cloud security concepts
- Experience using the AWS Management Console or AWS CLI.
- For hands on lab create account on [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
# Scenario Covered:
- Basics of IAM in AWS
- Implementing IAM Policies with Least Privilege to Manage S3 Bucket
- Objective: Create an S3 bucket with least privilege IAM policy and validate access.
- Steps:
- Create S3 bucket.
- Attach least privilege policy to IAM user.
- Validate access.
- Exploiting IAM PassRole Misconfiguration
-Allows a user to pass a specific IAM role to an AWS service (ec2), typically used for service access delegation. Then exploit PassRole Misconfiguration granting unauthorized access to sensitive resources.
- Objective: Demonstrate how a PassRole misconfiguration can grant unauthorized access.
- Steps:
- Allow user to pass IAM role to EC2.
- Exploit misconfiguration for unauthorized access.
- Access sensitive resources.
- Exploiting IAM AssumeRole Misconfiguration with Overly Permissive Role
- An overly permissive IAM role configuration can lead to privilege escalation by creating a role with administrative privileges and allow a user to assume this role.
- Objective: Show how overly permissive IAM roles can lead to privilege escalation.
- Steps:
- Create role with administrative privileges.
- Allow user to assume the role.
- Perform administrative actions.
- Differentiation between PassRole vs AssumeRole
Try at [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
The document discusses the instruction set of the 8085 microprocessor. It states that the 8085 has 246 instructions that are each represented by an 8-bit binary value called the op-code or instruction byte. It also mentions that an instruction is a binary pattern inside a microprocessor that performs a specific function, and the complete set of instructions a microprocessor supports is called its instruction set.
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...Codemotion
This document discusses extended differential fuzzing techniques. It begins with an overview of common fuzzing and differential fuzzing. Extended differential fuzzing aims to detect more vulnerability types by analyzing outputs across different implementations, inputs, versions, and operating systems. These include path disclosure, user disclosure, error disclosure, code evaluation, command execution, network connections, and file reads. The document demonstrates examples of detecting these behaviors in PHP, Perl, Python and other languages. It promotes an open source fuzzing framework called XDiFF that automates extended differential analysis.
This document discusses low-level input/output in C programming. It explains that low-level I/O provides direct access to files and devices using functions like open(), close(), read(), write(), and lseek(). These functions take a file descriptor as a parameter and allow accessing files sequentially or randomly. The document also covers error handling using errno values and differentiates between high-level and low-level I/O.
This document discusses C++ streams and stream classes. It explains that streams represent the flow of data in C++ programs and are controlled using classes. The key classes are istream for input, ostream for output, and fstream for file input/output. It provides examples of reading from and writing to files using fstream, and describes various stream manipulators like endl. The document also discusses the filebuf and streambuf base classes that perform low-level input/output operations.
This document discusses C++ stream classes and file input/output. It covers ios class functions and flags, manipulators, and user-defined output functions that format console I/O. It also discusses opening and reading/writing to files using ifstream, ofstream and fstream classes. Functions like get(), put(), read(), write(), seekg(), seekp(), tellg(), and tellp() are used to manipulate file pointers and perform I/O on files. Exceptions while accessing files and using command line arguments are also covered.
This document provides an overview of key concepts in C and C++ including:
1. The structure of a C/C++ program including main functions, declarations, statements, and preprocessor directives.
2. Basic data types like integers, floats, characters, and aggregates like arrays and structures.
3. Common programming constructs like selection, loops, functions and input/output.
4. Additional C++ topics like classes, inheritance and input/output streams.
5. Pointers and how they store the address of a variable in memory rather than the variable's value.
This document covers lecture 3 of a computer programming course. The lecture objectives are to understand why programmers use functions, how to define functions in Python, function calls and parameter passing. The document explains what functions are, benefits of using functions like simpler code, code reuse and better testing. It provides examples of defining functions, calling functions, using local variables within functions and passing arguments to functions. Exercises are included to demonstrate these concepts.
The document provides information about various Python concepts like PEP 8, pickling, lambda functions, generators, modules, packages and more. It also includes questions about memory management in Python, tools for static analysis, decorators, iterators, slicing, and other common Python interview questions.
The document discusses file handling in C++. It covers:
1) Using input/output files by opening, reading from, and writing to files. Files are interpreted as sequences of bytes and can be text or binary.
2) General file I/O steps which include declaring a file name variable, associating it with a disk file, opening the file, using it, and closing it.
3) Predefined console streams like cin, cout, cerr, and clog which are used for standard input, output, error output, and buffered error output respectively.
The document discusses file handling in C++. It covers:
1) Using input/output files by opening, reading from, and writing to files using streams. Streams act as an interface between files and programs.
2) General file I/O steps which include declaring a file name variable, associating it with a disk file, opening the file, using it, and closing it.
3) Predefined console streams like cin, cout, cerr, and clog which are opened automatically and connected to the keyboard, display, and error output respectively.
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
This document discusses file handling in C++. It defines a file as a collection of stored information, usually on a computer's disk. The main classes for file input/output in C++ are fstream, ifstream, and ofstream. It describes different file operations like opening, closing, reading from and writing to files. It also covers checking for the end of a file and different file opening modes. The two main types of files are text files, which are human-readable, and binary files, which store whole records at once in a non-readable format.
This document provides an overview of the Python programming language in 7 sentences or less:
The document outlines why Python is useful, how to run Python code, basic data types and operators in Python, statements and functions, and some useful Python packages and resources. It discusses that Python is an easy to learn, powerful, and portable programming language that supports object-oriented programming and is free and open source. The document also provides examples of running Python code directly from the interpreter and from script files.
The document discusses input/output files in Java. It covers the key classes used for reading and writing files in Java, including FileInputStream, FileOutputStream, FileReader, and FileWriter. It also discusses byte streams versus character streams, and provides examples of reading and writing to files in Java using these classes. Standard input/output streams like System.in and System.out are also covered.
This document provides an introduction to C++ programming. It begins with definitions of a computer, programming, and the C++ programming process. It then discusses hardware components like the CPU, memory, and input/output devices. It also covers software components like programming languages, operating systems, and the C++ development process. The document provides examples of C++ code and explanations of language features like variables, operators, and data types. It concludes with an overview of getting started with C++ input/output functions.
The type of a value refers to the kind of data it represents. In Python, the main types are:
- int - integer numbers like 1, 2, 100
- float - floating point numbers like 1.5, 3.14159
- str - strings, sequences of characters like 'hello'
- bool - boolean values True or False
When you write code, Python assigns a type to each value. The type determines how it can be used and what operations are valid on it. For example, you can add two integers but not add an integer to a string. Checking and understanding types is important for writing correct Python code.
The document discusses linkers and loaders, describing their functions in combining object files into executable files. It covers the ELF format, static vs dynamic linking, and how executable files are run using static or dynamic linkers. Key points include how static linkers resolve symbols and perform relocation, while dynamic linkers use shared libraries and handle relocation at runtime via the dynamic linker.
1. The document discusses object oriented programming concepts like classes, objects, inheritance, and polymorphism in C++.
2. It begins with an introduction to procedural programming and its limitations. Object oriented programming aims to overcome these limitations by emphasizing data over procedures and allowing for inheritance, polymorphism, and encapsulation.
3. The document then covers key OOP concepts like classes, objects, constructors, and static class members in C++. It provides examples of creating classes and objects.
This document provides information about file handling in C++. It discusses key concepts like input/output streams, opening and closing files, and different file types. Specifically, it covers:
- The different stream classes like fstream, ifstream, and ofstream that are used for file input/output.
- Opening and closing files using functions like open() and close(), and specifying open modes like ios::out.
- The two main types of files - text files that use character translations and binary files that store raw bytes.
- Basic file operations in C++ like reading, writing, and manipulating files using functions like read(), write(), seekp() etc.
- Examples of opening
Similar to C++ IOSTREAMS and Files OOPs using Adv C++ (20)
Null Bangalore | Pentesters Approach to AWS IAMDivyanshu
#Abstract:
- Learn more about the real-world methods for auditing AWS IAM (Identity and Access Management) as a pentester. So let us proceed with a brief discussion of IAM as well as some typical misconfigurations and their potential exploits in order to reinforce the understanding of IAM security best practices.
- Gain actionable insights into AWS IAM policies and roles, using hands on approach.
#Prerequisites:
- Basic understanding of AWS services and architecture
- Familiarity with cloud security concepts
- Experience using the AWS Management Console or AWS CLI.
- For hands on lab create account on [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
# Scenario Covered:
- Basics of IAM in AWS
- Implementing IAM Policies with Least Privilege to Manage S3 Bucket
- Objective: Create an S3 bucket with least privilege IAM policy and validate access.
- Steps:
- Create S3 bucket.
- Attach least privilege policy to IAM user.
- Validate access.
- Exploiting IAM PassRole Misconfiguration
-Allows a user to pass a specific IAM role to an AWS service (ec2), typically used for service access delegation. Then exploit PassRole Misconfiguration granting unauthorized access to sensitive resources.
- Objective: Demonstrate how a PassRole misconfiguration can grant unauthorized access.
- Steps:
- Allow user to pass IAM role to EC2.
- Exploit misconfiguration for unauthorized access.
- Access sensitive resources.
- Exploiting IAM AssumeRole Misconfiguration with Overly Permissive Role
- An overly permissive IAM role configuration can lead to privilege escalation by creating a role with administrative privileges and allow a user to assume this role.
- Objective: Show how overly permissive IAM roles can lead to privilege escalation.
- Steps:
- Create role with administrative privileges.
- Allow user to assume the role.
- Perform administrative actions.
- Differentiation between PassRole vs AssumeRole
Try at [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
Software Engineering and Project Management - Introduction, Modeling Concepts...Prakhyath Rai
Introduction, Modeling Concepts and Class Modeling: What is Object orientation? What is OO development? OO Themes; Evidence for usefulness of OO development; OO modeling history. Modeling
as Design technique: Modeling, abstraction, The Three models. Class Modeling: Object and Class Concept, Link and associations concepts, Generalization and Inheritance, A sample class model, Navigation of class models, and UML diagrams
Building the Analysis Models: Requirement Analysis, Analysis Model Approaches, Data modeling Concepts, Object Oriented Analysis, Scenario-Based Modeling, Flow-Oriented Modeling, class Based Modeling, Creating a Behavioral Model.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
artificial intelligence and data science contents.pptxGauravCar
What is artificial intelligence? Artificial intelligence is the ability of a computer or computer-controlled robot to perform tasks that are commonly associated with the intellectual processes characteristic of humans, such as the ability to reason.
› ...
Artificial intelligence (AI) | Definitio
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
1. Course Code CSE2001
Object Oriented Programming with C++
Type LTP
Credits 4
UNIT 5_ PART 2 : IOstreams and Fi les
OOPs using C++
2. Object Oriented Programming with C++
Course Code: CSE2001
UNIT 5 : CSE2001 IOstreams and Fi les
UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
3. C++ Files and Streams
A stream in simple words is flow of data.
C++ views each files as a stream.
The operations associated with files are
read and write
C++ provides various classes to support
these operations.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
4. Streams
• Stream: an object that either delivers data to its
destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)
– it acts as a buffer between the data source and
destination
• Input stream: a stream that provides input to a program
– System.in is an input stream
• Output stream: a stream that accepts output from a
program
– System.out is an output stream
• A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
5. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
6. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
7. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
8. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
9. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
10. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
11. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
12. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
13. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
14. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
15. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
16. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
17. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
18. Binary Versus Text Files
• All data and programs are ultimately just zeros and ones
– each digit can have one of two values, hence binary
– bit is one binary digit
– byte is a group of eight bits
• Text files: the bits represent printable characters
– one byte per character for ASCII, the most common code
– for example,CPP source files are text files
– so is any file created with a "text editor"
• Binary files: the bits represent other types of encoded
information, such as executable instructions or numeric data
– these files are easily read by the computer but not humans
– they are not "printable" files
• actually, you can print them, but they will be
unintelligible
• "printable" means "easily readable by humans when
printed"
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
19. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
20. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
21. To perform file processing in C++, the
header files essential are <iostream> and
<fstream>
<fstream> includes <ifstream> and
<ofstream>
ios is the base class for all these classes.
These classes provide several member
functions that perform input/output
operations.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
22. Abbreviated C++ class hierarchy for input output
streams
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
23. iostream -- contains basic information
required for all stream I/O operations
fstream -- contains information for
performing file I/O operations
iomanip -- contains information useful for
performing formatted I/O with parameterized
stream manipulators
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
24. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
25. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
26. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
27. How to open a file in C++ ?
ofstream outFile(“sample.dat”,
ios:out)
OR
ofstream outFile;
outFile.open(“sample.dat”, ios:out)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
28. How to close a file in C++?
The file is closed implicitly when a destructor
for the corresponding object is called
OR
by using member function close:
outFile.close();
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
29. File Open Modes
ios:: app - (append) write all output to the end
of file
ios:: ate - data can be written anywhere in the
file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open afile for output
ios: trunc -(truncate) discard the files’ contents
if it exists
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
30. File Open Modes
ios::nocreate - if the file does NOT exists, the
open operation fails
ios::noreplace - if the file exists, the open
operation fails
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
31. Reading and printing a sequential file
inFile >> var1 >> var2 >> var3
outFile<<“Name: “<<var1<<“Age :
“<<var2<<endl;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
32. 167
File position pointer
<istream> and <ostream> classes provide
member functions for repositioning the
file pointer (the byte number of the next
byte in the file to be read or to be written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class
33. Examples of moving a file pointer
inFile.seekg(0) - repositions the file get pointer to
the beginning of the file
inFile.seekg(n, ios:beg) - repositions the file get
pointer to the n-th byte of the file
inFile.seekg(m, ios:end) -repositions the file get
pointer to the m-th byte from the end of
file
inFile.seekg(0, ios:end) - repositions the file get
pointer to the end of the file
The same operations can be performed with
<ostream> function member seekp.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
34. Member functions tellg() and tellp()
Member functions tellg and tellp are provided
to return the current locations of the get and put
pointers, respectively.
long location = inFile.tellg();
To move the pointer relative to the current
location use ios::cur
inFile.seekg(n, ios::cur) - moves the file get
pointer n bytes forward.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
35. UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
36. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
37. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
38. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
39. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
40. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
41. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
42. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
43. • Manipulators are helping functions that can modify the
input/output stream.
• It does not mean that we change the value of a variable, it
only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.
• Manipulators are special functions that can be included in the
I/O statement to alter the format parameters of a stream.
• Manipulators are operators that are used to format the data
display.
• To access manipulators, the file iomanip.h should be included
in the program.
• For example, if we want to print the hexadecimal value of 100
then we can print it as:
• cout<<setbase(16)<<100
Types of Manipulators There are various types of manipulators:
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
44. Manipulators without arguments: The most important
manipulators defined by the IOStream library are provided
below.
endl: It is defined in ostream. It is used to enter a new line
and after entering a new line it flushes (i.e. it forces all the
output written on the screen or in the file) the output
stream.
ws: It is defined in istream and is used to ignore the
whitespaces in the string sequence.
ends: It is also defined in ostream and it inserts a null
character into the output stream. It typically works with
std::ostrstream, when the associated output buffer needs
to be null-terminated to be processed as a C string.
flush: It is also defined in ostream and it flushes the output
stream, i.e. it forces all the output written on the screen or
in the file. Without flush, the output would be the same, but
may not appear in real-time.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
45. C++ Stream I/O -- Stream Manipulators
C++ provides various stream manipulators
that perform formatting tasks.
Stream manipulators are defined in
<iomanip>
These manipulators provide capabilities for
setting field widths,
setting precision,
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
46. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
47. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
48. C++ Stream I/O -- Stream
Manipulators
setting and unsetting format flags,
flushing streams,
inserting a "newline" and flushing
output stream,
skipping whitespace in input stream
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
49. I/O -- Stream Manipulators
setprecision ( )
Select output precision, i.e., number of
significant digits to be printed.
Example:
cout << setprecision (2) ; // two
significant digits
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
50. I/O -- Stream Manipulators
setw ( )
Specify the field width (Can be used on
input or output, but only applies to next
insertion or extraction).
Example:
cout << setw (4) ; // field is four
positions wide
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
51. UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<)
and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
52. 5.3 overloading Inserters(<<) and
Extractors(>>)
overloading Inserters(<<)
• Programmers frequently overload the inserter
(or insertion) and extractor (or extraction)
operators because they are the main output
and input functions for C++ programs. Each
function follows a fixed pattern.
Example:
Int variable;
Cin>>variable;
Cout<< variable;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
53. example
friend ostream& operator<<(ostream& out, fraction
& f)
{
// format and print member variables of f
return out;
}
friend istream& operator>>(istream& in, fraction & f)
{
// read member variables of f
return in;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
54. • The patterns illustrated here assume that the
operator definitions are placed inside the class
(i.e., not just prototyped in the class).
• We must keep prototypes in the class, but we
can move the function bodies out of the class
by dropping the friend keyword.
• parts that cannot change: Both functions are
always implemented as friends
•operator<< always returns an ostream
reference has an ostream reference for the
first parameter operator>> always
• returns an istream reference has an istream
reference for the first parameter
• more flexible parts but still required by the
pattern:
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
55. • The second parameter for both operators is always
a class reference. The class name is always the
class for which the operator is overloaded
• programmer specified names:
• names for the ostream and istream reference
variables
• names for the output and input object reference
variables
• function specific operations:
• format and print member variables read values
from the input stream into the member variables
Both operators always end with a return
statement, and the returned value is always the
name of the first parameter
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
56. UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
57. C++ Files and Streams
• C++ views each files as a sequence of bytes.
• Each file ends with an end-of-file marker.
• When a file is opened, an object is created and a
stream is associated with the object.
• To perform file processing in C++, the header
files <iostream.h> and <fstream.h> must be
included.
• <fstream.> includes <ifstream> and <ofstream>
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
58. 193
5.4 Sequential and Random files
Updating a sequential file
• Data that is formatted and written to a
sequential file cannot be modified
easily without the risk of destroying
other data in the file.
• If we want to modify a record of data,
the new data may be longer than the old
one and it could overwrite parts of the
record following it.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
59. Problems with sequential files
Sequential files are inappropriate for so-called
“instant access” applications in which a
particular record of information must be
located immediately.
These applications include banking systems,
point-of-sale systems, airline reservation
systems, (or any data-base system.)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
60. Random access files
• Instant access is possible with random
access files.
• Individual records of a random access
file can be accessed directly (and
quickly) without searching many other
records.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
61. Sequential and Random files
• In a sequential access file, data is accessed in a linear,
sequential manner, from start to end. Each read or
write operation must follow the previous one.
• In contrast, in a random access file, data can be
accessed at any point in the file, without having to
read through the entire file first
• sequential access files
Simple and straightforward to implement, with
minimal hardware and software requirements. It is
inexpensive because it does not necessitate complex
indexing or search algorithms.
• Because data is stored in a linear fashion and can be
accessed predictably, it is extremely efficient for
dealing with large data sets.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
62. Parameter Sequential Access Random Access
Access Speed
Sequential access files are slower compared
to random access files since accessing a
specific record requires reading through all
the previous records in the file
Random access files, on the other hand, allow
direct access to specific records, resulting in
faster access times.
Access Method
Sequential access files allow access to
records in a sequential manner
Random access files allow direct access to
specific records using an index, record
number, or key.
Record Ordering
Sequential access files store records in a
specific order, usually the order in which
they were added to the file.
Random access files do not have any specific
order of storing records.
Insertion of New
Record
Inserting a new record in a sequential access
file is relatively easy since new records are
added to the end of the file.
Random access files may require relocating
other records to maintain the order so
insertion becomes hard as compared to
sequential access.
Memory
Requirements
Sequential access files require less memory
than random access files since they do not
need to store any indexing information.
Random access files require more memory
because of indexing information
Search Flexibility
Search flexibility is limited in sequential
access file.
Random access files offer higher search
flexibility than sequential access files since
they allow for direct access to specific records
based on various search criteria
Record Sizes
In sequential access files, record sizes are
usually uniform
Random access files, record sizes can be
variable
File Organization
Sequential access files are typically organized
in a linear fashion
Random access files are typically indexed.
Examples Text files, Logs Database, Spreadsheet
63. 198
Creating a sequential file
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream oC( "clients.dat", ios::out );
if ( !oC ) { // overloaded ! operator
cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}
cout << "Enter the account, name, and
balance.n"
<< "Enter end-of-file to end input.n? ";
int account;
char name[ 30 ];
float balance;
while ( cin >> account >> name >> balance )
{
oC<< account << ' ' << name
<< ' ' << balance << 'n';
cout << "? ";
}
return 0; // ofstream destructor closes file
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
64. 199
Creating a sequential file
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream outClientFile( "clients.dat", ios::out );
if ( !outClientFile ) { // overloaded ! operator
cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}
cout << "Enter the account, name, and
balance.n"
<< "Enter end-of-file to end input.n? ";
int account;
char name[ 30 ];
float balance;
while ( cin >> account >> name >> balance )
{
outClientFile << account << ' ' << name
<< ' ' << balance << 'n';
cout << "? ";
}
return 0; // ofstream destructor closes file
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
65. 200
Creating a sequential file
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream outClientFile( "clients.dat", ios::out );
if ( !outClientFile ) { // overloaded ! operator
cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
66. Sequential file
cout << "Enter the account, name, and balance.n"
<< "Enter end-of-file to end input.n? ";
int account;
char name[ 30 ];
float balance;
while ( cin >> account >> name >> balance ) {
outClientFile << account << ' ' << name
<< ' ' << balance << 'n';
cout << "? ";
}
return 0; // ofstream destructor closes file
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
67. How to open a file in C++ ?
Ofstream outClientFile(“clients.dat”, ios:out)
OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
68. File Open Modes
ios:: app - (append) write all output to the end of file
ios:: ate - data can be written anywhere in the file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open afile for output
ios: trunc -(truncate) discard the files’ contents if
it exists
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
69. 204
File Open Modes cont.
ios:nocreate - if the file does NOT exists, the open
operation fails
ios:noreplace - if the file exists, the open operation
fails
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
70. 205
How to close a file in C++?
The file is closed implicitly when a
destructor for the corresponding object is
called
OR
by using member function close:
outClientFile.close();
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
71. 206
Reading and printing a sequential file
// Reading and printing a sequential file
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
void outputLine( int, const char *, double );
int main()
{
// ifstream constructor opens the file
ifstream inClientFile( "clients.dat", ios::in );
if ( !inClientFile ) {
cerr << "File could not be openedn";
exit( 1 );
}
72. int account;
char name[ 30 ];
double balance;
cout << setiosflags( ios::left ) << setw( 10 ) << "Account"
<< setw( 13 ) << "Name" << "Balancen";
while ( inClientFile >> account >> name >> balance )
outputLine( account, name, balance );
return 0; // ifstream destructor closes the file
}
void outputLine( int acct, const char *name, double bal )
{
cout << setiosflags( ios::left ) << setw( 10 ) << acct
<< setw( 13 ) << name << setw( 7 ) << setprecision( 2 )
<< resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< bal << 'n';
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
73. 208
File position pointer
<istream> and <ostream> classes provide member
functions for repositioning the file pointer (the byte
number of the next byte in the file to be read or to be
written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
74. 209
Examples of moving a file pointer
inClientFile.seekg(0) - repositions the file get pointer
to the beginning of the file
inClientFile.seekg(n, ios:beg) - repositions the file get
pointer to the n-th byte of the file
inClientFile.seekg(m, ios:end) -repositions the file get
pointer to the m-th byte from the end of file
nClientFile.seekg(0, ios:end) - repositions the file get
pointer to the end of the file
The same operations can be performed with
<ostream> function member seekp.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
75. 210
Member functions tellg() and tellp().
Member functions tellg and tellp are provided to return
the current locations of the get and put pointers,
respectively.
long location = inClientFile.tellg();
To move the pointer relative to the current location use
ios:cur
inClientFile.seekg(n, ios:cur) - moves the file get pointer n
bytes forward.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
76. 211
Updating a sequential file
Data that is formatted and written to a
sequential file cannot be modified easily
without the risk of destroying other data in
the file.
If we want to modify a record of data, the
new data may be longer than the old one and
it could overwrite parts of the record
following it.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
77. Problems with sequential files
• Sequential files are inappropriate for so-called
“instant access” applications in which a particular
record of information must be located
immediately.
• These applications include banking systems, point-
of-sale systems, airline reservation systems, (or any
data-base system.)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
78. 213
Random access files
• Instant access is possible with random access files.
• Individual records of a random access file can be
accessed directly (and quickly) without searching
many other records.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
79. 214
Example of a Program that Creates a Random
Access File
// Fig. 14.11: clntdata.h
// Definition of struct clientData used in
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
float balance;
};
#endif
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
80. Creating a random access file
// Creating a randomly accessed file sequentially
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit1.dat", ios::out);
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
81. 216
clientData blankClient = { 0, "", "", 0.0 };
for ( int i = 0; i < 100; i++ )
outCredit.write
(reinterpret_cast<const char *>( &blankClient ),
sizeof( clientData ) );
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
82. 217
<ostream> memebr function write
The <ostream> member function write
outputs a fixed number of bytes beginning at
a specific location in memory to the specific
stream.
When the stream is associated with a file,
the data is written beginning at the location
in the file specified by the “put” file pointer.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
83. 218
Writing data randomly to a random
file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
84. 219
cout << "Enter account number "
<< "(1 to 100, 0 to end input)n? ";
clientData client;
cin >> client.accountNumber;
while ( client.accountNumber > 0 &&
client.accountNumber <= 100 ) {
cout << "Enter lastname, firstname, balancen? ";
cin >> client.lastName >> client.firstName
>> client.balance;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
85. 220
outCredit.seekp( ( client.accountNumber - 1 ) *
sizeof( clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );
cout << "Enter account numbern? ";
cin >> client.accountNumber;
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
86. 221
Reading data from a random file
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
ifstream inCredit( "credit.dat", ios::in );
if ( !inCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
87. 222
cout << setiosflags( ios::left ) << setw( 10 ) <<
"Account"
<< setw( 16 ) << "Last Name" << setw( 11 )
<< "First Name" << resetiosflags( ios::left )
<< setw( 10 ) << "Balance" << endl;
clientData client;
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
88. 223
while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client
),
sizeof( clientData ) );
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
89. 224
void outputLine( ostream &output, const clientData &c
)
{
output << setiosflags( ios::left ) << setw( 10 )
<< c.accountNumber << setw( 16 ) << c.lastName
<< setw( 11 ) << c.firstName << setw( 10 )
<< setprecision( 2 ) << resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< c.balance << 'n';
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
90. The <istream> function read
inCredit.read (reinterpret_cast<char *>(&client),
sizeof(clientData));
The <istream> function inputs a specified (by
sizeof(clientData)) number of bytes from the
current position of the specified stream into an
object.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
91. 226
Example of a Program that Creates
a Random Access File
/// Definition of struct clientData used in
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
float balance;
};
#endif
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
92. 227
Creating a random access file
// Creating a randomly accessed file sequentially
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit1.dat", ios::out);
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
93. 228
clientData blankClient = { 0, "", "", 0.0 };
for ( int i = 0; i < 100; i++ )
outCredit.write
(reinterpret_cast<const char *>(
&blankClient ),
sizeof( clientData ) );
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
94. 229
<ostream> member function write
The <ostream> member function write
outputs a fixed number of bytes
beginning at a specific location in
memory to the specific stream.
When the stream is associated with a
file, the data is written beginning at the
location in the file specified by the “put”
file pointer.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
95. 230
The write function expects a first
argument of type const char *, hence we
used the reinterpret_cast <const char
*> to convert the address of the
blankClient to a const char*.
The second argument of write is an
integer of type size_t specifying the
number of bytes to written. Thus the
sizeof( clientData ).
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
96. 231
Writing data randomly to a random
file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );
if ( !outCredit ) {
cerr << "File could not be opened." <<
endl;
exit( 1 );
} UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
97. cout << "Enter account number "
<< "(1 to 100, 0 to end input)n? ";
clientData client;
cin >> client.accountNumber;
while ( client.accountNumber > 0 &&
client.accountNumber <= 100 ) {
cout << "Enter lastname, firstname, balancen? ";
cin >> client.lastName >> client.firstName
>> client.balance;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
98. outCredit.seekp( ( client.accountNumber - 1 ) *
sizeof( clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );
cout << "Enter account numbern? ";
cin >> client.accountNumber;
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
99. 234
Reading data from a random file
#include <iostream>
#include <iomanip.h>
#include <fstream>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
ifstream inCredit( "credit.dat", ios::in );
if ( !inCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
100. cout << setiosflags( ios::left ) << setw( 10 ) <<
"Account"
<< setw( 16 ) << "Last Name" << setw( 11 )
<< "First Name" << resetiosflags( ios::left )
<< setw( 10 ) << "Balance" << endl;
clientData client;
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
101. while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
102. void outputLine( ostream &output, const
clientData &c )
{
output << setiosflags( ios::left ) << setw( 10 )
<< c.accountNumber << setw( 16 ) <<
c.lastName
<< setw( 11 ) << c.firstName << setw( 10 )
<< setprecision( 2 ) << resetiosflags(
ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< c.balance << 'n';
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
103. 238
The <istream> function read
inCredit.read (reinterpret_cast<char
*>(&client), sizeof(clientData));
The <istream> function inputs a specified
(by sizeof(clientData)) number of bytes
from the current position of the specified
stream into an object.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
104. Stream I/O Format State Flags
ios::showpointwhen set, show trailing decimal
point and zeros
ios::showpos when set, show the + sign
before positive numbers
ios::basefield
ios::dec use base ten
ios::oct use base eight
ios::hex use base sixteen
239
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
105. Stream I/O Format State Flags
ios::floatfield
ios::fixed use fixed number of digits
ios::scientific use "scientific" notation
ios::adjustfield
ios::left use left justification
ios::right use right justification
ios::internal left justify the sign, but right
justify the value
240
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
106. .setf ( )
Allows the setting of an I/O stream
format flag.
Examples:
// To show the + sign in front of
positive numbers
cout.setf (ios::showpos) ;
// To output the number in hexadecimal
cout.setf (ios::hex, ios::basefield) ;
241
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
107. UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects
into/from files
5.6 BINARY FILES
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
108. Need for FILES in C++
• Data is very important. Every organization depends
on its data for continuing its business operations.
• If the data is lost, the organization has to be closed.
• This is the reason computers are primarily created
for handling data, especially for storing and
retrieving data.
• In later days, programs are developed to process the
data that is stored in the computer.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
109. C++ FILES APPLICATION
• To store data in a computer, we need files.
• For example, we can store employee data like employee
number, name and salary in a file in the computer and
later use it whenever we want.
• Similarly, we can store student data like student roll
number, name and marks in the computer. In
computers’ view, a file is nothing but collection of data
that is available to a program.
• Once we store data in a computer file, we can retrieve it
and use it depending on our requirements.
•
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
110. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
111. ADVANTAGES OF STORING A DATA IN A
FILE
• When the data is stored in a file, it is stored
permanently.
• This means that even though the computer is switched
off, the data is not removed from the memory since the
file is stored on hard disk or CD.
• This file data can be utilized later, whenever required.
• It is possible to update the file data.
• For example, we can add new data to the existing file,
delete unnecessary data from the file and modify the
available data of the file. This makes the file more
useful.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
112. ADVANTAGES OF STORING A DATA IN A
FILE
• Once the data is stored in a file, the same data can
be shared by various programs.
• For example, once employee data is stored in a file,
it can be used in a program to calculate employees’
net salaries or in another program to calculate
income tax payable by the employees.
• Files are highly useful to store huge amount of data.
For example, voters’ list or census data.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
113. TYPES OF FILES
• In Python, there are two types of files.
• They are:
Text files
Binary files
• Text files store the data in the form of characters. For
example, if we store employee name “Ganesh”, it will
be stored as 6 characters and the employee salary
8900.75 is stored as 7 characters.
• Text files are used to store characters or strings.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
114. TYPES OF FILES
• Binary files store entire data in the form of bytes,
i.e. a group of 8 bits each.
• For example, a character is stored as a byte and an
integer is stored in the form of 8 bytes (on a 64 bit
machine). When the data is retrieved from the
binary file, the programmer can retrieve the data
as bytes.
• Binary files can be used to store text, images,
audio and video. Image files are generally available
in .jpg, .gif or .png formats.
• We cannot use text files to store images as the
images do not contain characters.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
115. TYPES OF FILES
• On the other hand, images contain pixels which are
minute dots with which the picture is composed of.
• Each pixel can be represented by a bit, i.e. either 1
or 0. Since these bits can be handled by binary files,
we can say that they are highly suitable to store
images. It is very important to know how to create
files, store data in the files and retrieve the data
from the files.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
116. MODES OF FILES
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
117. Binary file
• Binary file is a file with data stored in raw
format, the way it is stored in memory.
• For example, numbers are stored in binary
in memory.
• They are not converted to text (ASCII
characters) when writing to binary file.
• The data in binary format is not human
readable and cannot be read or modified
using text editors.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
118. • A binary file is a file whose content is
in a binary format consisting of a series
of sequential bytes, each of which is
eight bits in length.
• The content must be interpreted by a
program or a hardware processor that
understands in advance exactly how
that content is formatted and how to
read the data.
Binary file
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
119. • For example, only Microsoft Word and certain other
word processing programs can interpret
the formatting information in a Word
document.
• Executable files, compiled programs,
SAS and SPSS system files,
spreadsheets, compressed files, and
graphic (image) files are all examples
of binary files.
Binary file
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
120. Binary file
• To write a binary file in C++ use write method. It is
used to write a given number of bytes on the given
stream, starting at the position of the "put" pointer.
• The file is extended if the put pointer is current at
the end of the file. If this pointer points into the
middle of the file, characters in the file are
overwritten with the new data.
• If any error has occurred during writing in the file,
the stream is placed in an error state.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
121. Binary file
• Syntax of write method
• ostream& write(const char*,
int);
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
122. Binary file Example Code
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
123. Binary file Example Code
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
124. Student wstu[3];
wstu[0].roll_no = 1;
wstu[0].name = "Ram";
wstu[1].roll_no = 2;
wstu[1].name = "Shyam";
wstu[2].roll_no = 3;
wstu[2].name = "Madhu";
for(int i = 0; i < 3; i++)
wf.write((char *) &wstu[i], sizeof(Student));
wf.close();
if(!wf.good()) {
cout << "Error occurred at writing time!" <<
endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
125. cout<<"Student's Details:"<<endl;
for(int i=0; i < 3; i++) {
cout << "Roll No: " << s1[i].roll_no << endl;
cout << "Name: " << s1[i].name << endl;
cout << endl;
}
return 0;
}
Student s1[3];
s1[0].roll_no = 1;
s1[0].name = "Ram";
s1[1].roll_no = 2;
s1[1].name = "Shyam";
s1[2].roll_no = 3;
s1[2].name = "Madhu";
for(int i = 0; i < 3; i++)
wf.write((char *) &s1[i], sizeof(Student));
wf.close();
if(!wf.good()) {
cout << "Error occurred at writing time!" << endl;
return 1; }
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
127. In this Unit 5 we discussed the following
topics,
UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files