VINAY ALEXANDER PGT(CS) KV,SECL,JHAGRAKHAND. FILE :A file itself is a bunch of bytes stored on some storage device like tape, or magnetic disk etc. STREAM.

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.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
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.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
Dale Roberts 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
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 &
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.
Programming Principles II Lecture Notes 7 Files Andreas Savva.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
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.
Protectedly Inherited Base Class  When the access specifier of the base class in the derived class definition is protected, the base class is protectedly.
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.
DCT1063 Programming 2 CHAPTER 3 FILE INPUT AND FILE OUTPUT Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
VINAY ALEXANDER PGT(CS) KV,SECL,JHAGRAKHAND. FILE:A file itself is a bunch of bytes stored on some storage device like tape, or magnetic disk etc. STREAM:
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 Handling in C++.
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.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
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)
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
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++
CS212: Object Oriented Analysis and Design
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.
CPSC 231 D.H. C++ File Processing
FILE HANDLING IN C++.
File I/O with Records Lesson xx
Basic File I/O and Stream Objects
آشنایی با ساختارها و کار با فایلها
files Dr. Bhargavi Goswami Department of Computer Science
Chapter 13: Advanced File and I/O Operations
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
Data File Handling in C++
Data File Handling RITIKA SHARMA.
File I/O in C++ II.
Input/Output Streams, Part 2
Presentation transcript:

VINAY ALEXANDER PGT(CS) KV,SECL,JHAGRAKHAND

FILE :A file itself is a bunch of bytes stored on some storage device like tape, or magnetic disk etc. STREAM : A stream is a sequence of bytes. 1.The stream is a general name given to a flow of data at lowest level( at the lowest level, data is just the binary data without any notion of data type). 2. The stream that supplies data to the program is known as input stream. it reads the data from the file and hands it over to the program. the stream that received data from the program to known as output stram.it writes the received data to the file.

Disk File Program Output stream Input

filebuf : It sets the file buffers to read & write. close( ) & open( ) fstreambase : This is the base class for fstream, ifstream, ofstream classes. open( ) close( ) ifstream : input file stream class. It provide input operation for file. It inherit get( ), getline( ), read( ) and function supporting random access (seekg( ) and tellp( )) from istream class defined inside iostream.h ofstream : Output file stram class. It inherit put( ) and write( ) long with function supporting random access (seekp( ) and tellp( )) from ostream class defined class inside iostream.h fstream : It is a predefines a set of operations for handling file related input ad output. it is an I/O file stream class. It inherits all function from istream and ostream classes through iostream class defined inside iostream.h.

Files are required for storing the data and information permanently. the data files can be stored in two way. 1. Text file : A text file stores information in ASCII characters. Each line terminated by EOL ( end of line). In text files some internal translations take place when this EOL character is read or written. 2. Binary file : It stores information in the same format in which the information is held in memory. No delimiter for line. no translation occurs. It is faster and easier for a program read and write.

Opening of files can be achieved in two ways: 1.Using Constructor: 2.Using the function open( ) =>Using Constructor: ifstream input_file(“DataFile”); // create input object name as input_file char ch; input_file>>ch; float amt; input_file>>amt; ofstream output_file(“DataFile”); ”); // create output object name as output_file input_file.close( ); // close input connection to file output_file.close( ); // close output connection to file

ifstream filin; filin.open(“master.dat”); filin.close( );

S.NoConstantMeaningStream Type I ios::in: open file in read mode,ifstream ii ios::out: It open s file for writingi.e.,in output mode. ios::trunc ofstream iii ios::ate: seeks the to end of file upon opening of the file. Ofstream ifstream iv ios::app: appended to the endofstream V ios::trunc: pre-existing file destroyed and open file with zero length ofstream vi ios::nocreate: not create a new file when open ( ) fail, ofstream vii ios::noreplace: open( ) fail when file exists,ofstream viii ios::binary: Open a file in binary mode. By default it is text mode ofstream, ifstream

Both ios::ate and ios::app place you at end of the file just opened.the ios::app mode allowes you to add data to the end of the file only, while the ios::ate mode lets you write data anywhere in the file, even over old data. stream _object.open(“filename”,(filemode)); ofstream fout; fout.open(“data.dat”,ios::binary | ios:app); fout.close( );

There are five steps to use file in your C++ program are: 1. Determine the type of link required. 2. Declare a stream for the desired type of link. 3. Attach the desired file to the stream. 4. Now process as required. 5. Close the file-link with stream.

1. Determine the type of link required. (i) File to memory input (IN To the Memory) (ii) Memory to File output (OUT FROM the Memory) (iii)Both input/output

2. Declare a stream for the desired type of link. File to memoryifstream fin Memory to Fileofstream fout Bothfstream finout ifstream fi; // stream name here is fi ofstream fo; // stream name here is fo fstream fio; // stream name here is fio

3.Attach the desired file to the stream. ifstream fin(“data.dat”); //using constructor Or fin.open(“data.dat”, ios::in); //using open( ) ofstream fout(“oput.txt”); Or fout.open(“oput.txt”, ios::out); fstream finout(“Newfile.txt”); Or finout.open(“Newfile.txt”, ios::in | ios::out);

4.Now process as required for the given problem. //get rollnumbers and marks of the students of a class and store these details //into a file called marks.dat. #include void main( ) { ofstream fout; fout.open(“mark.dat”, ios::out); char ans=‘y’; int rollno; while(ans==‘y’ || ans==‘Y’) { cout<<“\nEnter roll no : “; cin>>rollno; fout<<rollno; cout<<“\n Want to enter more? :”; cin>>ans; } fout.close( ); }

5.Close the file-link with stream. fin.close( ); fout.close( );

#include void main() { clrscr(); ofstream fout("student"); char name[30],ch; float marks=0.0; for(int i=0;i<5;i++) { cout<<"students"<<(i+1)<<":\t Name:"; cin.get(name,30); cout<<"\tmarks:"; cin>>marks; cin.get(ch);

fout<<name<<'\n'<<marks<<'\n'; } fout.close(); ifstream fin("student"); fin.seekg(0); cout<<"\n"; for(i=0;i<5;i++) { fin.get(name,30); fin.get(ch); fin>>marks; fin.get(ch); cout<<"student name:"<<name; cout<<"\t marks:"<<marks<<"\n"; } fin.close(); getch(); }

#include void main( ) { ofstream fout; fout.open(“mark.dat”,ios::out); int rollno; for(int i=0;i<5;i++) { cout<<“\nEnter roll no : “; cin>>rollno; fout<<rollno<<“\n”; } fout.close( ); ifstream fin(“mark.dat”); fin.seekg(0); cout<<“\n”; for(i=0;i<5;i++) { fin.get(rollno); fin>>rollno; cout<<rollno; }

Sequential I/O with Files: 1.The get() function read a single character from associated tream and puts that values in ch. It returns a reference to the stream. (i) istream & get (char & ch); (ii) istream & get(char * buf, int num, char delim=‘\n’) cin.get( line, 40,’$’); (iii) int get(); 2.The put() function writes the value of ch to stream and returns a reference to the stream. (i) ostream & put(char ch);

//program to display contents of a file using get() function. #include int main( ) { char ch; ifstream fin; ifstream fin(“marks.dat”, ios::in); if(!fin) { cout<<“Can’t open”; return 1; } while(fin) { fin.get(ch); cout<<ch; } fin.close( ); return 0; }

The getline() function: It reads characters and puts them in the array pointed to by buf until either num characters have been read. and removes the delimiter new line character from the input stream. istream & getline(char *buf,int num,char delim=‘\n’);

Reading and writing blocks of binary data is to use read() and write() function. The Read() function reads sizeof(buf) bytes from the associated stream and puts them in the buffer pointed to by buf istream & read((char *) &buf, int sizeof(buf)); The write() function writes sizeof(buf) bytes to the associated stream from the buffer pointed to by buf. ostream & write((char *) &buf, int sizeof(buf)); fin.read((char *) &savec, sizeof(customer)); fout.write((char *) &savec, sizeof(customer));

//WAP to write and read a structure using write() and read() function using a binary file. #include struct customer{ char name[51]; float balance; }; void main( ) { customer savac; strcpy(savac.name, “tina”); savac balance= ; ofstream fout; fout.open(“saving”,ios::out | ios::binary); if(!fout) { cout<<“can’t open” ; return 1; } fout.write((char *) &savac, sizeof(customer)); fout.close( ); ifstream fin; fin.open(“saving”,ios::in | ios:: binary); fin.read((char *) &savac, sizeof(customer)); cout<<savac.name<<“ has the balance amount of Rs.”<<savac.balance<<“\n”; fin.close( ); }

=>Reading and writing class objects: The function read() and write can also be used for reading and writing class objects. these functions handle the entire structure of an object as a single unit. Only data members are written t the disk file and not the member functions.

//WAP for reading and writing class object. #include class Student { char name[51]; char grade; float marks; public: void getdata(void); Void display(void); }; Void Student:: getdata(void) Char ch;

void main( ) { customer savac; strcpy(savac.name, “tina”); savac balance= ; ofstream fout; fout.open(“saving”,ios::out | ios::binary); if(!fout) { cout<<“can’t open” ; return 1; } fout.write((char *) &savac, sizeof(customer)); fout.close( ); ifstream fin; fin.open(“saving”,ios::in | ios:: binary); fin.read((char *) &savac, sizeof(customer)); cout<<savac.name<<“ has the balance amount of Rs.”<<savac.balance<<“\n”; fin.close( ); }

Detecting EOF: this function detect the end of the file is reached. Prototype int eof( ); It returns nonzero when the end of the file has been reached,otherwise it returns zero.  File pointers and random access: Random access is achieved by manipulating seekg( ),seekp( ),tellg( ) and tellp( )function.  The seekg( ) and tellg( ) functions allow to set and examine the get_pointer, and seekp( ) and tellp( ) functions perform these operations on the put_pointer.

The seekg( ) and tellg( ) functions are for input stream (ifstream) and seekp( ) and tellp( ) functions are for output streams (ofstream) Syntax: seekg() –istream & seekg(long); #1 - istream & seekg(long,seek_dir); #2 seekp() –oftream & seekp(long); #1 - oftream & seekp(long,seek_dir); #2 (seek_dir takes the definition enum seek_dir{beg,cur,end } ;) tellg( )- long tellg( ) tellp( )- long tellp( )

Basic operations on Binary Files: 1.Searching: There are two method to search a record in Binary file. (a). With records implemented through structures (b). With records implemented through classes

//WAP to searching in a file that has records maintained through structure. #include struct stu { int rollno; char name[25]; char class[4]; float marks; char grade; } s1; void main( ) { int rn;char found =‘n’; Ifstream fi(“stu.dat”,ios::in); cout<“”enter rollno to be search for:”; cin>>rn; While(!fin.eof( ) ) { Fi.read((char *) &s1,sizeof(s1)); If(s1.rollno==rn) { Cout<<s1.name<“,rollno:”<<rn<<“has”<<s1.marks<<“% marks and “<<s1.grade<<“grade”<<endl; Found=‘y’; Break; } If(found==‘y’) Cout<<“Rollno not found in file”<<endl; Fin.close( ); }

Appending data: To append data in a file, the file opened with the following two specifications; (i). File is opened in output mode (ii). File is opened in ios::app mode. If file opened in ios::app mode, the previous record /information is retained and new data gets appended to the file.

#include Class stu{ int rollno; char name[25],class[4],grade; float marks; public: void getdata( ) { cout >rollno; cout >name; Cout >class; Cout >grade; If(marks>=75) grade=‘A’; else If(marks>=60) grade=‘B’; else if(marks>=50) grade=‘C’; else if(marks>=40) grade=‘D’; else grade=‘F’; } Void putdata( ) { cout<<name<<rollno<<marks<<grade<<endli; } int getrno( ) { return rollno; } } s1;

void main( ) { ofstream fo(“stu.dat”,ios::app); Char ans=‘y’; While(ans==‘y’) { S1.getdata( ); Fo.write((char *) &s1,sizeof(s1)); Cout<<“record added to the file \n”; Cout<<“enter more record\n”; Cin>.ans; } fo.close( ); }

Inserting data in sorted File: To insert data in a sorted file. To follow the following steps. 1 Determining the appropriate position. 2.Copy the records to prior to determined position to a temporary file say temp.dat. 3. Append the new record in the temporary file temp.dat. 4. Now append the rest of the records in temporary file temp.dat. 5. Delete file stu.dat by issuing command. remove(“stu.dat”); 6.Remove file temp.dat as follows : rename(“temp.dat”,”stu.dat”);

Deleting a Record :To delete record, following procedure is carried out : 1. Firstly, determine the position of the record to be deleted, by performing a search in the file. 2. Keep copying the records other than the record to be deleted in a temporary file say temp.dat. 3. Do not copy the record to be deleted to temporary file, temp.dat. 4. Copy rest of the records to temp.dat. 5. Delete original file say stu.dat as : remove(“stu.dat”); 6. Rename temp.dat as stu.dat as : rename (“temp.dat”,”stu.dat”);

Modifying Data  To modify a record, the file is opened in I/O mode and an important step is performed that gives the beginning address of record being modified. After the record is modified in memory, the file pointer is once again placed at the beginning position of this record and then record is rewritten. Following code illustrates it : class stu {: //same as before void modify() ; }s1 ; //get new data here fstream fio; fio.open (“stu.dat”, ios ;; in ! Ios ;; out), “Read rollno whose data is to be modified” ;

long pos ; while(! Fio.eg()) {pos = fio.tellg( ) ; //determine beginnig position of record fio.read((char *) & s1, sizeof(s1)). if (s1.getrno( ) == rn) //this is the record to be modified. {s1.Modify ( ) ; //get new data fio.seekg(pos) ; //place file pointer at the beginning record position fio.write((char *) & s1, sixeof (s1)) ; //now write modified record }

ERROR Handling during file I/O: Name Meaning eofbit -> 1 when end of file is encountered, 0 otherwise eailbit -> 1 when a non-fatal I/O error has occurred, 0 otherwise badbit -> 1 when a fatal I/O error has occurred, 0 otherwise goodbit -> 0 value

Function Meaning int bad ( )  Return non zero value.if an invalid operation is attemted or any unrecoverable error occurred.otherwise 0. int eof()  Return non zero value.if end of file is encountered while reading otherwise 0. int fail( )  Return non zero when an input or output operation failed int good( )  Return non zero if no error occurred this means,alll the above functions are false.otherwise 0. clear ( )  Reset the error state so that further operations can be attempted.