T2_U5_Sequential_Read_Write
T2_U5_Sequential_Read_Write
· C++ allows the file manipulation command to access the file sequentially or randomly.
· The data of the sequential file should be accessed sequentially , that is , one character at a time.
· In order to access the nth number of bytes, all previous characters are read and ignored.
· There are number of functions to perform read and write opearations with the files.
· Some functions read/write single characters and some functions read/write a single characters,
and some functions read/write blocks of binary data.
· The put() and get() functions are used to read or write a single character , whereas write() and
read() are used to read or write blocks of binary data.
put() - function
· The function put() to writes a character to the specified file by the stream object.
· The put() function places a character in the file indicated by the put pointer.
get() function
· This function reads a single character from the file pointed by the get pointer, that is , the
character at the current get pointer position is caught by the get() function
Write a program to write and read string to the file using put() and get() functions
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<string.h>
void main()
clrscr();
fstream fp;
char str[100];
int i=0;
char ch;
cin.getline(str,50);
fp.open("krish.txt",ios::in | ios::out);
while(i[str]!='\0')
fp.put(str[i++]);
fp.seekg(0);
while(fp)
fp.get(ch);
cout<<ch;
fp.close();
getch();
}
read() and write() opeartors
· The read() and write() functions perform read and write operations in a binary format that is
exactly the same as an internal representation of data in the computer.
· Due to the capabilities of these functions , large data can be stored in a small amount of
memory.
· Both these functions are also used to write and read class object to and from files.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
clrscr();
int num[]={100,120,130,140,150,160};
ofstream out;
out.open("one.bin");
out.write((char *) &num,sizeof(num));
out.close();
getch();
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
clrscr();
int num[90];
ifstream in;
in.open("one.bin");
in.read((char *) &num,sizeof(num));
for(int i=0;i<6;i++)
cout<<"\n"<<num[i];
getch();