Wednesday, April 9, 2008

C++ Technical Interview solved questions - 4

1.Differentiate between functions read() and write().
Ans. Functions read() and write() are used for reading and writing blocks of binary data to a file. Their prototypes are

istream &read(unsigned char *buf, int num);
ostream &write(const unsigned char *buf, int num);

The read() function reads num bytes from the associated stream and puts them in the buffer pointed to by buf. The write() function writes num bytes to the associated stream from the buffer pointed to by buf.

2. Assuming the class FLOPPYBOX, write a function in C++ to perform following:
(i) Write the objects of FLOPPYBOX to a binary file.
(ii) Reads the objects of FLOPPYBOX from binary file and display them on screen.
class FLOPPYBOX
{
int size;
char name[10];
public:
void getdata(){cin>>size;gets(name);}
void showdata(){cout<write_file();
clrscr();
cout<<"Reading from a binary file"<read_file();
getch();
}
void write_file()
{
fstream f1;
f1.open("floppy.dat",ios::app,ios::binary);
obj.getdata();
f1.write((char*) &obj,sizeof(FLOPPYBOX));
f1.close();
}
void read_file()
{
fstream f1;
f1.open("floppy.dat",ios::in,ios::binary);
while(!f1.eof())
{
f1.read((char*) &obj,sizeof(FLOPPYBOX));
obj.showdata();
}
f1.close();
}

Keep watching for more C++ and other computer languages solved technical interview questions with answers and programs / solutions free online here, tutorials, school and college project questions, admission interview questions, software developers job interview questions, etc. here only on PreviousPapers.blogspot.com

No comments: