Ds lec 14 filing in c++

21
Filing in C++ Filing in C++ Lecture # 14 Lecture # 14

Transcript of Ds lec 14 filing in c++

Page 1: Ds lec 14 filing in c++

Filing in C++Filing in C++

Lecture # 14Lecture # 14

Page 2: Ds lec 14 filing in c++

Stream ClassesStream Classes

A stream is a general name given to a flow A stream is a general name given to a flow of data.of data.

A stream is represented by an object of a A stream is represented by an object of a particular class.particular class.

Example: cin and cout stream objects.Example: cin and cout stream objects. Different streams are used to represent Different streams are used to represent

different kinds of data flow.different kinds of data flow. Example: ifstream class represent data Example: ifstream class represent data

flow from input disk files.flow from input disk files.

Page 3: Ds lec 14 filing in c++

The Stream Class HierarchyThe Stream Class Hierarchy

ios

ostreamistream

iostreamifstream ofstream

fstream

Page 4: Ds lec 14 filing in c++

Formatted File I/OFormatted File I/O

In formatted I/O, numbers are stored on In formatted I/O, numbers are stored on disk as a disk as a series of charactersseries of characters..

This can be inefficient for numbers with This can be inefficient for numbers with many digits.many digits.

However, it is easy to implement.However, it is easy to implement. Characters and strings are stored more or Characters and strings are stored more or

less normally.less normally.

Page 5: Ds lec 14 filing in c++

Formatted File I/OFormatted File I/O

#include<iostream>#include<iostream>

#include<fstream>#include<fstream>

#include<string>#include<string>

using namespace std;using namespace std;

int main()int main()

{{

char ch='x';char ch='x';

int j = 77;int j = 77;

double d = 6.02;double d = 6.02;

string str1 = "kafka";string str1 = "kafka";

string str2 = "proust";string str2 = "proust";

ofstream outfile("fdata.txt");ofstream outfile("fdata.txt");

outfileoutfile << ch<< ch

<< j<< j

<< ' '<< ' '

<< d<< d

<< str1<< str1

<< ' '<< ' '

<< str2;<< str2;

cout<<"file written"<<endl;cout<<"file written"<<endl;

return 0;return 0;

}}

Page 6: Ds lec 14 filing in c++

Formatted File I/OFormatted File I/O We created an object of ofstream and initialized We created an object of ofstream and initialized

it to the file FDATA.TXT.it to the file FDATA.TXT. This initialization sets aside various resources This initialization sets aside various resources

for the file, and accesses or opens the file of that for the file, and accesses or opens the file of that name on the disk.name on the disk.

If the file does not exist, it is created.If the file does not exist, it is created. If it does exist, it is truncated and the new data If it does exist, it is truncated and the new data

replaces the old.replaces the old. The outfile object acts much as cout object.The outfile object acts much as cout object. So we can use the insertion operator (<<) to So we can use the insertion operator (<<) to

output variables of any basic type to the file.output variables of any basic type to the file.

Page 7: Ds lec 14 filing in c++

Formatted File I/OFormatted File I/O

When the program terminates, the outfile object goes out When the program terminates, the outfile object goes out of scope. This calls its destructor, which closes the file, of scope. This calls its destructor, which closes the file, so we don’t need to close the file explicitly.so we don’t need to close the file explicitly.

We must separate numbers with nonnumeric characters.We must separate numbers with nonnumeric characters. Strings must be separated with white spaces.Strings must be separated with white spaces. This implies that strings cannot contain imbedded This implies that strings cannot contain imbedded

blanks.blanks. Characters need no delimiters, since they have a fixed Characters need no delimiters, since they have a fixed

length.length.

Page 8: Ds lec 14 filing in c++

Formatted File I/OFormatted File I/O

int main()int main()

{{

char ch;char ch;

int j;int j;

double d;double d;

string str1;string str1;

string str2;string str2;

ifstream infile("fdata.txt");ifstream infile("fdata.txt");

infile >> chinfile >> ch>> j>> j>> d>> d>> str1>> str1>> str2;>> str2;

cout<<ch<<endlcout<<ch<<endl<<j<<endl<<j<<endl<<d<<endl<<d<<endl<<str1<<endl<<str1<<endl<<str2<<endl;<<str2<<endl;

return 0;return 0;}}

Page 9: Ds lec 14 filing in c++

Strings with Embedded BlanksStrings with Embedded Blanks

To handle strings with embedded blanks, we need to To handle strings with embedded blanks, we need to write a specific write a specific delimiterdelimiter character after each string, and character after each string, and use the use the getline()getline() function, rather than the extraction function, rather than the extraction operator, to read them in.operator, to read them in.

This function reads characters, including white-space, This function reads characters, including white-space, until it encounters the ‘\n’ character, and places the until it encounters the ‘\n’ character, and places the resulting string in the buffer supplied as an argument. resulting string in the buffer supplied as an argument. The maximum size of the buffer is given as the second The maximum size of the buffer is given as the second argument.argument.

Page 10: Ds lec 14 filing in c++

Strings with Embedded BlanksStrings with Embedded Blanks

int main()int main()

{{

ofstream outfile("test.txt");ofstream outfile("test.txt");

outfile<< "I fear thee, ancient Mariner!outfile<< "I fear thee, ancient Mariner!\n\n";";

outfile<< "I fear thy skinny handoutfile<< "I fear thy skinny hand\n\n";";

return 0;return 0;

}}

Page 11: Ds lec 14 filing in c++

Strings with Embedded BlanksStrings with Embedded Blanks

int main()int main(){{const int MAX=80;const int MAX=80;char buffer[MAX];char buffer[MAX];ifstream infile("test.txt");ifstream infile("test.txt");whilewhile(!infile.eof())(!infile.eof())

{{infile.getline(buffer,MAX);infile.getline(buffer,MAX);cout<<buffer<<endl;cout<<buffer<<endl;}}

return 0;return 0;}}

Page 12: Ds lec 14 filing in c++

Binary I/OBinary I/O

When storing large amount of data, it is more efficient to When storing large amount of data, it is more efficient to use binary I/O.use binary I/O.

In binary I/O, numbers are In binary I/O, numbers are stored as they are in the stored as they are in the computer’s RAM memorycomputer’s RAM memory, rather than as strings of , rather than as strings of characters.characters.

write()write(), a member of ofstream, and , a member of ofstream, and read()read(), a member of , a member of ifstream are used.ifstream are used.

These functions think about data in terms of bytes (type These functions think about data in terms of bytes (type char).char).

They don’t care how the data is formatted, they simply They don’t care how the data is formatted, they simply transfer a buffer full of bytes from and to a disk file.transfer a buffer full of bytes from and to a disk file.

Page 13: Ds lec 14 filing in c++

Binary I/OBinary I/O

The parameters to write() and read() are The parameters to write() and read() are the the address of the data buffer and its address of the data buffer and its lengthlength..

The address must be cast, using The address must be cast, using reinterpret_castreinterpret_cast, to type char*, and the , to type char*, and the length is the length is the length in byteslength in bytes (characters), (characters), not the number of data items in the buffer.not the number of data items in the buffer.

Page 14: Ds lec 14 filing in c++

Binary I/OBinary I/O

int main()int main(){{const int MAX=100;const int MAX=100;int j;int j;int buff[MAX];int buff[MAX];for(j=0; j<MAX; j++)for(j=0; j<MAX; j++)

buff[j]=j;buff[j]=j;ofstream os("test.dat", ofstream os("test.dat",

ios::binary);ios::binary);os.write(reinterpret_cast<chaos.write(reinterpret_cast<cha

r*>(buff), MAX*sizeof(int));r*>(buff), MAX*sizeof(int));os.close();os.close();

for(j=0; j<MAX; j++)for(j=0; j<MAX; j++)buff[j]=0;buff[j]=0;

ifstream is("test.dat", ifstream is("test.dat", ios::binary);ios::binary);

is.read(reinterpret_cast<char*is.read(reinterpret_cast<char*>(buff), MAX*sizeof(int));>(buff), MAX*sizeof(int));

for(j=0; j<MAX; j++){for(j=0; j<MAX; j++){if(buff[j]!=j)if(buff[j]!=j)

{cerr<<"data is {cerr<<"data is incorrect"<<endl;}incorrect"<<endl;}

}}cout<<"data is correct"<<endl;cout<<"data is correct"<<endl;return 0;return 0;}}

Page 15: Ds lec 14 filing in c++

Binary I/OBinary I/O We must use the We must use the ios::binaryios::binary argument in the argument in the

second parameter to constructor when working second parameter to constructor when working with binary data.with binary data.

We need to use the reinterpret_cast operation to We need to use the reinterpret_cast operation to make it possible for a buffer of type int to look to make it possible for a buffer of type int to look to the read() and write() functions like a buffer of the read() and write() functions like a buffer of type char.type char.

The reinterpret_cast operator is how we tell the The reinterpret_cast operator is how we tell the compiler. “I know you won’t like this, but I want compiler. “I know you won’t like this, but I want to do it anyway.”to do it anyway.”

It changes a section of memory without caring if It changes a section of memory without caring if it makes sense.it makes sense.

Page 16: Ds lec 14 filing in c++

Object I/OObject I/O

We can also write objects, of user defined We can also write objects, of user defined classes, to files.classes, to files.

Similarly, we can read objects from files.Similarly, we can read objects from files. When writing an object we generally want When writing an object we generally want

to use to use binary modebinary mode.. This writes the same bit configuration to disk This writes the same bit configuration to disk

that was stored in memorythat was stored in memory and ensures that numerical data contained in and ensures that numerical data contained in

objects is handled properly.objects is handled properly.

Page 17: Ds lec 14 filing in c++

Example: Object I/OExample: Object I/O

#include<iostream>#include<iostream>using namespace std;using namespace std;class Personclass Person{{private:private:

char name[40];char name[40];int age;int age;

public:public:void readData()void readData()

{{cout<<"Enter name: ";cout<<"Enter name: ";

cin>>name;cin>>name;

cout<<"Enter age: ";cout<<"Enter age: ";

cin>>age;cin>>age;

}}

void showData()void showData()

{{

cout<<name<<endlcout<<name<<endl

<<age<<endl;<<age<<endl;

}}

};};

Page 18: Ds lec 14 filing in c++

Example: Object I/OExample: Object I/O

#include"person.h"#include"person.h"#include<iostream>#include<iostream>#include<fstream>#include<fstream>#include<string>#include<string>using namespace std;using namespace std;int main()int main(){{Person p;Person p;p.readData();p.readData();ofstream os("person.dat", ofstream os("person.dat",

ios::binary);ios::binary);

os.write(reinterpret_cast<char*os.write(reinterpret_cast<char*>(&p), sizeof(Person));>(&p), sizeof(Person));

os.close();os.close();

Person p1;Person p1;ifstream is("person.dat", ifstream is("person.dat",

ios::binary);ios::binary);is.read(reinterpret_cast<char*>(is.read(reinterpret_cast<char*>(

&p1), sizeof(Person));&p1), sizeof(Person));p1.showData();p1.showData();return 0;return 0;}}

Page 19: Ds lec 14 filing in c++

I/O with Multiple ObjectsI/O with Multiple Objects

int main() {int main() {

char ch;char ch;

Person p;Person p;

fstream file;fstream file;

file.open("group.dat",ios::app | ios::out | ios::in | ios::binary);file.open("group.dat",ios::app | ios::out | ios::in | ios::binary);

dodo {{

p.readData();p.readData();

file.write(reinterpret_cast<char*>(&p), sizeof(Person));file.write(reinterpret_cast<char*>(&p), sizeof(Person));

cout<<"Enter another person(y/n)? : "<<endl;cout<<"Enter another person(y/n)? : "<<endl;

cin>>ch;cin>>ch;

}while(ch=='y');}while(ch=='y');

Page 20: Ds lec 14 filing in c++

I/O with Multiple ObjectsI/O with Multiple Objects

file.seekg(0);//reset to start of filefile.seekg(0);//reset to start of file

file.read(reinterpret_cast<char*>(&p), sizeof(Person));file.read(reinterpret_cast<char*>(&p), sizeof(Person));

whilewhile(!file.eof())(!file.eof())

{{

cout<<"\nPerson: ";cout<<"\nPerson: ";

p.showData();p.showData();

file.read(reinterpret_cast<char*>(&p), sizeof(Person));file.read(reinterpret_cast<char*>(&p), sizeof(Person));

}}

return 0;return 0;

}}

Page 21: Ds lec 14 filing in c++

I/O with Multiple ObjectsI/O with Multiple Objects

If we want to create a file stream object If we want to create a file stream object that can be used for both, reading to and that can be used for both, reading to and writing from a file, we need to create an writing from a file, we need to create an object of object of fstreamfstream class. class.

open()open() function is a member of the function is a member of the fstream class.fstream class.

We can create a stream object once, and We can create a stream object once, and can open it repeatedly.can open it repeatedly.