Data File Handling RITIKA SHARMA.

Slides:



Advertisements
Similar presentations
By Sumit Kumar Gupta PGT(CS) KV NO.1, 1st Shift, BBSR.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
DATA FILE HANDLING. Contents to be covered in class  Concept of files & streams  Stream class hierarchy  File handling functions  Text V/S Binary.
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output stream.
Dale Roberts 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
FILE HANDLING IN C++.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
File handling in C++ BCA Sem III K.I.R.A.S. Using Input/Output Files Files in C++ are interpreted as a sequence of bytes stored on some storage media.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
File I/O. fstream files File: similar to vector of elements Used for input and output Elements of file can be –character (text)struct –object (non-text.
C++ FILE I/O.
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.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
File Handling. Read data from file and display it on screen #include int main() { /* fin object is created with parameterzied constructor */ ifstream.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
1 CSC241: Object Oriented Programming Lecture No 32.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
Learners Support Publications Working with Files.
Lecture 14 Arguments, Classes and Files. Arguments.
FILE HANDLING(WORKING WITH FILES) FILE- A file is a collection of related data stored in a particular area on the disk. STREAMS- interface between the.
Binary Files. Text Files vs. Binary Files Text files: A way to store data in a secondary storage device using Text representation (e.g., ASCII characters)
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.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Data File Handling in C++ Data File Handling in C++ Paritosh Srivastava PGT (Comp. Science) Kendriya VidyalayaJoshimath.
KBD Program with file I/O Operation File Disk Program with file I/O Operation Screen Cin Cout.
File Handling. Read data from file and display it on screen #include int main() { /* fin object is created with parameterzied constructor */ ifstream.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
Programming with ANSI C ++
17 File Processing.
Tutorial4us.com File Handling in C++ Tutorial4us.com.
Data File Handling in C++
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.
C ++ MULTIPLE CHOICE QUESTION
Copyright © 2003 Pearson Education, Inc.
CPSC 231 D.H. C++ File Processing
FILE HANDLING IN C++.
آشنایی با ساختارها و کار با فایلها
files Dr. Bhargavi Goswami Department of Computer Science
Chapter 13: Advanced File and I/O Operations
Sequential input and output Operations in file
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Sindhu S PGT Comp.Sc. K V Kollam
File I/O in C++ I.
Data File Handling in C++
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
File I/O in C++ II.
File I/O in C++ I.
Input/Output Streams, Part 2
Presentation transcript:

Data File Handling RITIKA SHARMA

Files A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform the read and write operations on these files A program involves either or both of following kinds of data communication: Data transfer between the console unit and the program Data transfer between the program and a disk file RITIKA SHARMA

Console-program-file interaction RITIKA SHARMA

Introduction Computer programs are associated to work with files as it helps in storing data & information permanently. File - itself a bunch of bytes stored on some storage devices. In C++ this is achieved through a component header file called fstream.h The I/O library manages two aspects- as interface and for transfer of data. The library predefine a set of operations for all file related handling through certain classes. RITIKA SHARMA

A stream refers to a flow of data. Classified in 2 categories: C++ provides a new technique for handling I/O operations through mechanism known as streams. A stream refers to a flow of data. Classified in 2 categories: Output stream Input stream In output stream flow of data is from program to the output device. In input stream the flow of data is from input device to a program in main memory. RITIKA SHARMA

File Input and output streams RITIKA SHARMA

Classes for file stream operations The I/O system of C++ contains a set of classes that define the file handling methods. These include: ifstream ofstream fstream These classes are derived from fstreambase and from corresponding iostream class RITIKA SHARMA

Stream classes for file operations System defined streams User defined streams Stream classes for file operations RITIKA SHARMA

File I/O streams Input Stream Disk files Program Output stream RITIKA SHARMA

ios ostream istream streambuf iostream ifstream fstream ofstream filebuf fstream Base RITIKA SHARMA

A file can be opened in two ways: Using constructor function A file stream can be defined using classes ifstream, ofstream, and fstream. A file can be opened in two ways: Using constructor function Using member function RITIKA SHARMA

Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs. We need to know: how to "connect" file to program how to tell the program to read data how to tell the program to write data error checking and handling EOF RITIKA SHARMA

Filename The file name is a string of characters that make up a valid filename for the operating system. It has two parts, a primary name and an optional period with extension Example: Input.data Test.doc RITIKA SHARMA

Opening a file For opening a file, we must first create a file stream and then link it to the filename. A file stream can be defined using the classes ifstream, ofstream and fstream that are contained in the header file fstream A file can be opened in two ways: Using a constructor function of the class Using the member function open() of the class RITIKA SHARMA

Opening files using constructor Constructor is used to initialize an object while it is being created. Here, a filename is used to initialize the file stream object. This involves following steps: Create a file stream object to manage the stream using appropriate class Initialize the file object with the desired filename. RITIKA SHARMA

For example: ofstream outfile(“results”); // output only This creates outfile as an ofstream object that manages the output stream. This statement opens the file results and attaches it to the output stream outfile RITIKA SHARMA

The following statement declares infile as an ifstream object and attaches it to the file data for reading ifstream infile (“data”); //input only The program may contain statements like: outfile<<total; outfile<<sum; infile>>number; infile>>string RITIKA SHARMA

We can also use same file for both reading and writing data Program1 …….. ofstream outfile(“salary”); //creates outfile and connects “salary” to it ……... Program2 ………. ifstream infile(“salary”); //creates infile and connects “salary” to it ……… RITIKA SHARMA

Instead of using two program, one for writing data and another for reading data, we can use single program to do both operations on file. ….. outfile.close(); //disconnect salary file from outfile ifstream infile(“salary”); // and connect to infile infile.close(); RITIKA SHARMA

example #include<fstream.h> #include<iostream.h> main() { char name[30]; float cost; ofstream outf(“item”); cout<<“enter item name”; cin>>name; outf<<name; cout<<“enter cost”; cin>>cost; outf<<cost<<“\n”; outf.close(); ifstream inf(“item”); inf>>name; inf>>cost; cout<<”item name”<<name; cout<<“item cost”<<cost; inf.close(); getch(); } RITIKA SHARMA

Opening file using Open() This function is used to open multiple files that uses same stream object. Syntax:- file_stream class stream_object; stream_object.open(“filename”); RITIKA SHARMA

outfile.open(“Data1”); ………………….. outfile.close(); ofstream outfile; outfile.open(“Data1”); ………………….. outfile.close(); outfile.open(“Data2”); ……………………. RITIKA SHARMA

cout<<“contents of country file”; while(fin) #include<fstream.h> #include<iostream.h> main() { ofstream fout; fout.open(“country”); fout<<“usa\n”; fout<<“uk\n”; fout<<“india\n”; fout.close(); fout.open(“capital”); fout<<“washinton\n”; fout<<“london\n”; const int n=80; char line[n]; ifstream fin; fin.open(“country”); cout<<“contents of country file”; while(fin) { fin.getline(line,n); cout<<line; } fin.close(); fin.open(“capital”); cout<<“contents of capital file”; getch(); RITIKA SHARMA

Detecting end-of-file This condition is necessary for preventing any further attempt to read data from the file. while(fin) here fin is ifstream object which returns a value 0 if any error occur in file including end-of-file condition. if(fin1.eof()!=0) { exit(1);} eof() is a member function of class ios. It returns non zero value if the end-of-file(eof) condition is encountered and zero otherwise. RITIKA SHARMA

Reading from files simultaneously fin1.getline(line,size); cout<<"capital of"<<line; if(fin2.eof()!=0) { cout<<"exit from capital\n"; exit(1); } fin2.getline(line,size); cout<<line<<endl; getch(); #include<fstream.h> #include<iostream.h> #include<conio.h> #include<stdlib.h> main() { const int size=80; char line[size]; ifstream fin1, fin2; fin1.open("country"); fin2.open("capital"); for(int i=1;i<=3;i++) if(fin1.eof()!=0) { cout<<"exit from country\n"; exit(1); } RITIKA SHARMA

Open(): File Modes We can have two arguments in open(), to specify the file- mode. stream-object.open(“filename”,mode); the second argument mode specifies the purpose for which file is opened and mode known as file mode parameter. RITIKA SHARMA

Go to end of file on opening Parameter Meaning ios::app Append to end-of-file ios::ate Go to end of file on opening ios::binary Binary file ios::in Open file for reading only ios::nocreate Open fail if file does not exist ios::noreplace Open fail if file already exist ios::out Open file for writing only ios::trunc Delete contents of file RITIKA SHARMA

fileout.open(“hello”,ios::app); void main() { fstream infile; fstream fileout; fileout.open(“hello”,ios::app); void main() { fstream infile; Infile.open(“data_file”, ios::in|ios::out) ---- ----- } RITIKA SHARMA

RITIKA SHARMA

File pointers and their Manipulations Each file has two associated pointers known as the file pointers. Input pointer/get pointer Output pointer/put pointer RITIKA SHARMA

Default actions In read only mode the Input pointer is automatically set at the beginning. In write only mode, the existing contents are deleted and output pointer is set at the beginning. In append mode, the output pointer moves to the end of file. RITIKA SHARMA

File opened in read mode: File opened in write mode: I/p pointer automatically set at beginning. File opened in write mode: Existing contents deleted & O/p pointers sets at beginning. To add more data, file is opened in append mode. RITIKA SHARMA

Functions for manipulation of file pointer To move the file pointer to any other desired position inside the file. The file stream classes support the following to manage such situations: seekg()- moves get pointer to specified location seekp()- moves put pointer to specified location tellg()- gives the current position of get pointer tellp()- gives the current position of put pointer RITIKA SHARMA

Example ofstream file1; file1.open(“result”, ios::app); int p=file1.tellp(); The value of p will represent the number of bytes in the file. Infile.seekg(10); Moves the file pointer to the byte number 10. RITIKA SHARMA

Specifying the offset seekg(offset, refposition); seekp(offset, refposition); Offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. refposition can be: ios::beg ios::cur ios::end RITIKA SHARMA

Some sample pointer offset Pointer offset calls RITIKA SHARMA

Sequential input and output operations put(),get() used to handle single character at a time. write(), read() functions are used to handle a stream of data. file.put(string); file.get(ch); RITIKA SHARMA

main() { char string[80]; cout<<“enter a string”; cin>>string; int len= strlen(string); fstream file; file.open(“text”, ios::in|ios::out); for(i=0;i<len;i++) file.put(string[i]); file.seekg(0); char ch; while(file) {file.get(ch); cout<<ch; }} RITIKA SHARMA

write() and read() infile.read((char *)&V, sizeof(V)); outfile.write((char *)&V, sizeof(V)); These functions take two arguments, first is address of variable V, second is length of that variable in bytes. RITIKA SHARMA

Example main() { float height[4]={175.5,153.0}; ofstream outfile; outfile.open(filename); outfile.write(( char *)& height,sizeof(height)); outfile.close(); RITIKA SHARMA

Reading and Writing Class object The binary input output read() and write() are designed to write and read from disk file objects. These functions handles entire structure of an object as a single unit . function write() copies a class object from memory byte by byte with no conversion. RITIKA SHARMA

Example void main() { fstream file; inventory iobj; file.open(“STOCK”, ios:: in|ios::out); cout<<“enter detail for items”; iobj.readdata(); file.write((char*) & iobj,sizeof(iobj)); File.seekg(0); file.read((char*) & iobj ,sizeof(iobj)); iobj.writedata(); file.close(); } RITIKA SHARMA

Updating a file Updating means to perform following tasks: Displaying the contents of file Modifying the existing file Adding a new item Deleting an existing item. RITIKA SHARMA

Size of each object can be obtained using: int ob_len= sizeof(object); These actions require the file pointers to move to a particular location. This can be easily implemented if file contains objects of equal length. Size of each object can be obtained using: int ob_len= sizeof(object); Then location of desired object is:- int location=m*ob_len; RITIKA SHARMA

total number of objects in a file:- int n=file_size/ob_len; RITIKA SHARMA

ERROR HANDLING FUNCTION RETURN VALUE AND MEANING eof() returns true (non zero) if end of file is encountered while reading; otherwise return false(zero) fail() return true when an input or output operation has failed bad() returns true if an invalid operation is attempted or any unrecoverable error has occurred. good() returns true if no error has occurred. RITIKA SHARMA